以编程方式填充DataGridView组合框单元格
本文关键字:组合 单元格 DataGridView 填充 编程 方式 | 更新日期: 2023-09-27 18:19:37
我有一个winforms中的DataGridView,它包含一个组合框列。网格视图以编程方式填充,并且在开始时为空。"列表"是一个包含自定义对象的列表。值1/2/3对于每一行都是唯一的。
int[] array = new[] {value1,value2,value3}
for (int i = 0; i < list.Count; i++)
{
DataRow newrow = MyDataTable.NewRow();
newrow["idColumn"] = list[i].Customer_id;
newrow["dateoforderColumn"] = list[i].Customer_date;
newrow["commColumn"] = list[i].Customer_comment;
// This is what I want, and can't get to work.
newrow["comboColumn"] = array;
// I have also tried (newrow["comboColumn"] as DataGridViewComboColumn).DataSource
// but it didn't work either.
MyDataTable.Rows.Add(newrow);
}
如何填充新创建的组合框单元格?此外,我需要在for循环中执行此操作,因为我需要索引来获取数据。
从代码的外观来看,您只需要设置一个值数组。在这种情况下,您只需要为列设置一次,而不是为每一行设置,我通常在构造函数中或填充行之前这样做。
//Clear any junk items that may have been there from the designer or previous view
((DataGridViewComboBoxColumn)MyDataTable.Columns["comboColumn"]).Items.Clear();
//Add you new values
((DataGridViewComboBoxColumn)MyDataTable.Columns["comboColumn"]).Items.AddRange(array);
然后设置新行单元格的值
//Set value to be selected in new row
newrow["comboColumn"] = list[i].Customer_value;