组合框数据绑定C#WinForms

本文关键字:C#WinForms 数据绑定 组合 | 更新日期: 2023-09-27 18:29:06

我有两个表:诊断:ID,名称诊断患者:患者ID,诊断ID。

我有一个带有2个组合框的DateGridView:第一个组合框需要显示诊断的ID,第二个需要显示名称。当我在DataGridView中添加新行时,我收到一个异常,说诊断ID不能为null(尽管我选择了第一个组合框上的ID)。

我正在使用此代码将组合框添加到我的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绑定到DiagnoseForPatients数据表。如何绑定诊断ID?在WPF VB.NET上我使用:

cmb.SelectedValueBinding = New Binding("DiagnoseID")

我应该如何在WinForms上写它?

组合框数据绑定C#WinForms

一列足以处理"诊断"信息

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);

关于诊断ID不能为空的异常

看起来像是DiagnoseID列的属性AllowDbNull = false

设置DataColumn.AllowDbNull = true或者为列设置DataColumn.DefaultValue = 1或其他默认值

如果您没有访问DataTable的列,那么您可以在DataGridView1.DefaultValuesNeeded事件处理程序中为新行设置默认值

private void DataGridView1_DefaultValuesNeeded(Object sender, DataGridViewRowEventArgs e)
{
    int comboBoxColumnIndex = 1;
    int diagnoseIDDefaultValue = 1;
    e.Row.Cells[ComboBoxColumnIndex].Value = diagnoseIDDefaultValue;
}