Search code examples
c#datatabledatagridselectedindex

Datatable - SelectedIndex in Combobox


Is it possible to add selectedIndex for combobox in dataTable in loop ?

 DataGridViewComboboxColumn dataGrid = new DataGridViewComboboxColumn();
 datagrid.Datasource = enumData; //this works 
 datagrid.Name = "cmb"

 Datatable dt = new DataTable();
 dt.Columns.Add("cmb");
 for(int i = 0, i<200, i++)
 {
    var data = GetData(i);
    DataRow r =new DataRow();
    r["cmb] = data.value; //selectedIndex??

 }

Solution

  • If you're using a datagridview bound to a datatable, you don't mess with the individual combo boxes in the grid. You do something like this (I'll include the setup code):

    DataTable sourceData = new DataTable();
    sourceData.Columns.Add("Name");
    sourceData.Columns.Add("Gender", typeof(int));
    
    sourceData.Rows.Add("John", 1);
    sourceData.Rows.Add("Jane", 2);
    sourceData.Rows.Add("Xxxx", 3);
    
    
    DataTable comboData = new DataTable();
    comboData.Columns.Add("Disp");
    comboData.Columns.Add("Valu", typeof(int));
    
    
    comboData.Rows.Add("Male", 1);
    comboData.Rows.Add("Female", 2);
    comboData.Rows.Add("Unspecified", 3);
    

    And now for the nuts and bolts of it:

    dataGridView1 = new DataGridView();
    dataGridView1.DataSource = sourceData;
    
    //binding the dgv will create a couple of textbox columns, 
    //now let's add a combo column to demo the binding concept
    
    
    DataGridViewComboboxColumn dgvcbcGender = new DataGridViewComboboxColumn();
    dgvcbcGender.Datasource = comboData; //refers to the male/female/unspecified table
    dgvcbcGender.DisplayMember = "Disp"; //show john/jane/Xxxx in the combo
    dgvcbcGender.ValueMember = "Valu"; //use the 1/2/3 ints as values to be stored in the sourceData table
    dgvcbcGender.DataPropertyName = "Gender"; //critical! == "read the `Gender` int value of the row in `sourceData`, look it up in the `Valu` column of `comboData`
    

    It is the last line that connects the list of items in the combo with the data in the main table. When binding is done like this we don't mess witht he selctedIndex of any combo at all; the combo will display the Male/Female/Unspecified related to the 1/2/3 it finds in the base row (sourceData.Gender) - it does this by looking up the value 1/2/3 in the comboData.Valu column. When you set a new Gender, it will take the corresponding SelectedValue out of the comboData.Valu and store it back in the row. You have another column bound to sourceData.Gender - see it change also when you change the setting in the combo box (maybe have to navigate to another row)

    Now just make sure you add the column to the datagridview:

    dataGridView1.Columns.Add(dgvcbcGender);