我创建了一个像这样的通用数据表,这很好:
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;
}
但我需要一个comboBoxColumn有不同的数据源在数据网格的每一行,所以我参考一些解决方案试图设置列和数据源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
}
现在字符串列是空的,那么它究竟应该如何实现?
您没有设置实际的列Name
属性,您已经设置了DataPropertyName
属性
一旦你设置了comboCol.Name
属性,当做:
var comboCol = new DataGridViewComboBoxColumn
{
HeaderText = "combo1",
DataPropertyName = "combo1",
Name = "combo1"
};
你可以这样做:
var comboCell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells[comboCol.Name];
comboCell.DataSource = comboDic[i];
comboCell.Value = "n";
添加注释:您也可以使用comboCol.Index
属性,它将为您提供列索引。