0
votes

I have 2 Tables: Diagnose: ID, Name DiagnoseForPatients: PatientID, DiagnoseID.

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

I'm using this code to add the ComboBox's to my 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. The DataGridView Is binded to DiagnosesForPatients DataTable. How can I bind the DiagnoseID? ON WPF VB.NET I use:

cmb.SelectedValueBinding = New Binding("DiagnoseID")

How should I Write it on WinForms?

1

1 Answers

1
votes

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

Seems like DiagnoseID column's property AllowDbNull = false.

Set DataColumn.AllowDbNull = true Or set DataColumn.DefaultValue = 1 or some other default value for column

If you haven't access to the DataTable's column, then you can set default values for new rows in the DataGridView1.DefaultValuesNeeded eventhandler

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