【问题标题】:ComboBox DataBinding C# WinForms组合框数据绑定 C# WinForms
【发布时间】:2016-01-06 13:18:18
【问题描述】:

我有 2 张桌子: 诊断:ID、姓名 DiagnoseForPatients:PatientID、DiagnoseID。

我有一个带有 2 个 ComboBoxes 的 DateGridView:第一个 ComboBox 需要显示诊断的 ID,第二个需要显示名称。 当我向 DataGridView 添加新行时,出现异常,提示 DiagnoseID 不能为空(尽管我在第一个 ComboBox 上选择了 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 绑定到 DiagnosesForPatients DataTable。 如何绑定 DiagnoseID? 在 WPF VB.NET 上我使用:

cmb.SelectedValueBinding = New Binding("DiagnoseID")

WinForms上应该怎么写?

【问题讨论】:

    标签: c# winforms combobox


    【解决方案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);
    

    关于DiagnoseID 不能为空的异常

    看起来像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;
    }
    

    【讨论】:

    • 但是如果我需要同时显示 - DiagnoseID 和 DiagnoseName 怎么办?
    • 然后创建另一个具有不同DisplayMember 的列,就像您在问题中所做的那样。 DataPropertyName 是重点
    猜你喜欢
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 2011-08-25
    • 1970-01-01
    • 2010-11-22
    • 2013-12-24
    • 1970-01-01
    相关资源
    最近更新 更多