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?
You haven't set the actual Columns
Nameproperty, you have set theDataPropertyNamepropertyOnce you set the
comboCol.Nameproperty, when doing:You can then do:
Added note: You can also use the
comboCol.Indexproperty too which will give you the Column Index.