ComboBox DataBinding C#WinForms

时间:2016-01-06 13:18:19

标签: c# winforms combobox

我有2个表: 诊断:ID,名称 DiagnoseForPatients:PatientID,DiagnoseID。

我有一个带有2个ComboBox的DateGridView:第一个ComboBox需要显示诊断的ID,第二个需要显示名称。 当我向DataGridView添加一个新行时,我得到一个例外,说诊断ID不能为空(尽管我在第一个ComboBox上选择了ID)。

我正在使用此代码将ComboBox添加到我的DataGridView:

     ClinicTableAdapters.DiagnoseTableAdapter daDiagnoses = new ClinicTableAdapters.DiagnoseTableAdapter();
     Clinic.DiagnoseDataTable dtDiagnosesAdd = daDiagnoses.GetData();

     DgDiagnosesAdd.AutoGenerateColumns = false;
     col1.HeaderText = "ID";
     col1.DataPropertyName = "ID";
     col1.Name = "ID";
     col1.ValueMember = "ID";
     col1.DisplayMember = "ID";
     col1.DataSource = dtDiagnosesAdd;
     DgDiagnosesAdd.Columns.Add(col1);

     col2.HeaderText = "Name";
     col2.DataPropertyName = "Name";
     col2.Name = "Name";
     col2.ValueMember = "Name";
     col2.DisplayMember = "Name";
     col2.DataSource = dtDiagnosesAdd;
     DgDiagnosesAdd.Columns.Add(col2);

我正在使用DataGridView为患者添加诊断。 DataGridView绑定到DiagnosesForPatients DataTable。 如何绑定DiagnoseID? 在WPF VB.NET上我使用:

cmb.SelectedValueBinding = New Binding("DiagnoseID")

我应该如何在WinForms上编写它?

1 个答案:

答案 0 :(得分:1)

一栏足以处理“诊断”信息

DgDiagnosesAdd.AutoGenerateColumns = false;
col1.HeaderText = "Diagnose";
//Next line will bind DiagnoseForPatients.DiagnoseID to Diagnose.ID
col1.DataPropertyName = "DiagnoseID";
col1.Name = "DiagnosesDiagnoseID";
col1.ValueMember = "ID";
col1.DisplayMember = "Name"; //Name column will be used as display text
col1.DataSource = dtDiagnosesAdd;
DgDiagnosesAdd.Columns.Add(col1);

关于 Exception,说诊断ID不能为空

似乎是DiagnoseID列的属性AllowDbNull = false

设置DataColumn.AllowDbNull = true 或者为列

设置DataColumn.DefaultValue = 1或其他一些默认值

如果您无法访问DataTable的列,则可以在DataGridView1.DefaultValuesNeeded eventhandler

中为新行设置默认值
private void DataGridView1_DefaultValuesNeeded(Object sender, DataGridViewRowEventArgs e)
{
    int comboBoxColumnIndex = 1;
    int diagnoseIDDefaultValue = 1;
    e.Row.Cells[ComboBoxColumnIndex].Value = diagnoseIDDefaultValue;
}