How to bind DataTable with different combobox items each row to DataGridView?

263 Views Asked by At

I created a general DataTable like this, it's fine :

    BindingSource bindingSource1 = new BindingSource();
    bindingSource1.DataSource = CreateDataTable();
    dataGridView1.DataSource = bindingSource1;

    private DataTable CreateDataTable()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add(new DataColumn("String1"));
        dt.Columns.Add(new DataColumn("String2"));
        DataRow dr = dt.NewRow(); dr["String1"] = "a"; dr["String2"] = "aa"; dt.Rows.Add(dr);
                dr = dt.NewRow(); dr["String1"] = "b"; dr["String2"] = "bb"; dt.Rows.Add(dr);
        //...
        return dt;
    }

But I need a comboBoxColumn which has different datasource each row in datatablegrid, so I refer to some solutions tried to set Columns and DataSource to datagridview :

    dataGridView1.AutoGenerateColumns = false;
    dataGridView1.Columns.Add("String1", "String1");
    dataGridView1.Columns.Add("String2", "String2");
    DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
    comboCol.HeaderText = comboCol.DataPropertyName = comboCol.Name= "combo1";// fixed by ConnorTJ
    dataGridView1.Columns.Add(comboCol);
    
    bindingSource1.DataSource = CreateDataTable();
    dataGridView1.DataSource = bindingSource1;
    
    Dictionary<int, List<string> > comboDic = new Dictionary<int, List<string> >() {
    { 0, new List<string>() { "1", "11", "111" } },
    { 1, new List<string>() { "2", "22", "222" } } };
    for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
    {
        DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells["combo1"];
        comboCell.DataSource = comboDic[i];
        //comboCell.Value = "n";//set the value out of items will throw error
    }

Now the string columns are empty, So how exactly should it be achieved?

1

There are 1 best solutions below

1
ConnorTJ On

You haven't set the actual Columns Name property, you have set the DataPropertyName property

Once you set the comboCol.Name property, when doing:

var comboCol = new DataGridViewComboBoxColumn
            {
                HeaderText = "combo1",
                DataPropertyName = "combo1",
                Name = "combo1"
            };

You can then do:

var comboCell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells[comboCol.Name];
comboCell.DataSource = comboDic[i];
comboCell.Value = "n";

Added note: You can also use the comboCol.Index property too which will give you the Column Index.