如何绑定一个复选框列表与属性在我的类?



我正在创建一个有两个表单的应用程序,一个是为了理解我选择的是哪个文件,第二个是之前做一个过滤器,这意味着你可以选择你想在这个文件中看到的属性。我有一个复选框列表和类与我的属性。

我也有一个按钮在我的第一个表单,我有:

foreach (var item in ds)
{
DataGridViewRow row = new DataGridViewRow();
fileListDataGridView.Rows.Add(
item.Path,
item.PatientName,
item.PatientID);
}

我不确定这是如何从DataGridWiev列表中添加数据的正确方法,但现在我有这个解决方案。因为它只是在列表的末尾添加了一个新项。

问题是我在第二个表单中有checkedListBox,我需要以某种方式将它与我的属性绑定。

属性:

public string Path { get; set; }
public string PatientName { get; set; }
public string PatientID { get; set; }

当您单击带有Patient Name的复选框时,这意味着您将在第一个表单中获得只有此属性的信息。我知道当我们创建一个checkedListBox时,我们也有一个索引,但我如何获得这个索引并将它与我的prop绑定?

不熟悉DataGridView编程的人倾向于摆弄DataGridView的行和单元格。这很麻烦,难以理解,难以重用,并且很难进行单元测试。

使用数据绑定更容易。

显然你想在你的DataGridView中显示Patient的几个属性。

class Patient
{
public int Id {get; set;}
public string Name {get; set;}
public string Path {get; set;}
... // other properties?
}

使用visual studio你已经添加了一个DataGridView和你想要显示的列。在表单的构造函数中:

public MyForm()
{
InitializeComponent();
// assign Patient properties to the columns:
this.columnId.DataPropertyName = nameof(Patient.Id);
this.columnName.DataPropertyName = nameof(Patient.Name);
this.columnPath.DataPropertyName = nameof(Patient.Path);
... // etc.
}

在表单的某个地方,你有一个方法来获取必须显示的Patients:

IEnumerable<Patient> FetchPatientsToDisplay()
{
... // TODO: implement; out-of-scope of this question
}

我们使用BindingList来显示Patients:

BindingList<Patient> DisplayedPatients
{
get => (BindingList<Patient>)this.dataGridView1.DataSource;
set => this.dataGridView1.DataSource = value;
}

现在要在加载表单时填充DataGridView:

void OnFormLoading(object sender, ...)
{
this.ShowPatients();
}
void ShowPatients()
{
this.DisplayedPatients = new BindingList<Patient>(this.FetchPatientsToDisplay().ToList());
}

就这些!显示病人;如果允许,操作员可以添加/删除/编辑Patients。编辑完成后,按下OKApply Now按钮通知程序:

void ButtonOk_Clicked(object sender, ...)
{
// Fetch the edited Patients:
ICollection<Patient> editedPatients = this.DisplayedPatients;
// find out which patients are changed and process them
this.ProcessPatients(editedPatients);
}

所以你不需要自己添加/删除行。通常是操作员这样做的。如果默认的Patient不足以显示,请使用事件BindingList。AddningNew:

void OnAddingNewPatient(object sender, AddingNewEventArgs e)
{
// create a new Patient and give it the initial values that you want
e.NewObject = new Patient()
{
Id = 0,   // zero: this Patient has no Id yet, because it is not added to the database yet
Name = String.Empty,
Path = String.Empty,
}
}

也许下面的属性是有用的:

Patient CurrentPatient => (Patient) this.dataGridView1.CurrentRow?.DataBoundItem;

如果你允许多重选择:

IEnumerable<Patient> SelectedPatients = this.dataGridView1.SelectedRows
.Cast(row => row.DataGridViewRow)
.Select(row => row.DataBoundItem)
.Cast<Patient>();

换句话说:将datagridView中的每个选定行解释为DataGridViewRow。从每个DataGridViewRow获取绑定到它的项。我们知道这是一个Patient,所以我们可以将它强制转换为一个Patient。

最新更新