[英]ComboBox DataBinding C# WinForms
I have 2 Tables: Diagnose: ID, Name DiagnoseForPatients: PatientID, DiagnoseID. 我有2个表:诊断:ID,名称诊断:患者ID,诊断ID。
I have A DateGridView with 2 ComboBoxes: First ComboBox needs to show the ID of the Diagnose, And the second one needs to show the name. 我有一个带有2个ComboBox的DateGridView:第一个ComboBox需要显示诊断的ID,第二个ComboBox需要显示名称。 When I'm adding a new row to my DataGridView I'm Getting an Exception saying DiagnoseID Can't be null (although I chose ID On first ComboBox). 当我在DataGridView中添加新行时,我得到一个异常,说明DiagnoseID不能为null(尽管我在第一个ComboBox上选择了ID)。
I'm using this code to add the ComboBox's to my DataGridView: 我正在使用以下代码将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);
I'm using the DataGridView For Adding Diagnoses For patient. 我正在使用DataGridView为患者添加诊断。 The DataGridView Is binded to DiagnosesForPatients DataTable. DataGridView绑定到DiagnosesForPatients DataTable。 How can I bind the DiagnoseID? 如何绑定DiagnoseID? ON WPF VB.NET I use: 在WPF VB.NET上,我使用:
cmb.SelectedValueBinding = New Binding("DiagnoseID")
How should I Write it on WinForms? 我应该如何在WinForms上编写它?
One column is enough for handling "Diagnose" information 一列足以处理“诊断”信息
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);
About Exception saying DiagnoseID Can't be null 关于Exception的DiagnoseID不能为null
Seems like DiagnoseID
column's property AllowDbNull = false
. 好像DiagnoseID
列的属性AllowDbNull = false
。
Set DataColumn.AllowDbNull = true
Or set DataColumn.DefaultValue = 1
or some other default value for column 设置DataColumn.AllowDbNull = true
或设置DataColumn.DefaultValue = 1
或其他一些列的默认值
If you haven't access to the DataTable's column, then you can set default values for new rows in the DataGridView1.DefaultValuesNeeded
eventhandler 如果您无法访问DataTable的列,则可以在DataGridView1.DefaultValuesNeeded
事件处理程序中为新行设置默认值。
private void DataGridView1_DefaultValuesNeeded(Object sender, DataGridViewRowEventArgs e)
{
int comboBoxColumnIndex = 1;
int diagnoseIDDefaultValue = 1;
e.Row.Cells[ComboBoxColumnIndex].Value = diagnoseIDDefaultValue;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.