我有一个DataGridView
的列作为ComboBox
这是我用来创建我的列,然后更新每个行DataSource
的代码。DataGridViewComboBoxCell数据源空
var dTable = new DataTable();
dTable.Columns.Add("Id",typeof(int));
dTable.Columns.Add("Desc", typeof(string));
for (int i = 0; i < 10; i++)
{
var dRow = dTable.NewRow();
dRow[0] = i;
dRow[1] = "test";
dTable.Rows.Add(dRow);
}
dataGridView1.DataSource = dTable;
//Create the ComboBoxColumn at the end of the grid
var cmb = new DataGridViewComboBoxColumn();
cmb.Name = "ComboCol";
cmb.HeaderText = "ComboCol";
dataGridView1.Columns.Add(cmb);
UpdateDataSourceCombo();
private void UpdateDataSourceCombo()
{
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
var comboCell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells["ComboCol"];
//Same datasource for every row just for testing
comboCell.DataSource = new string[] { "a", "b", "c" };
}
}
该列正确创建为ComboBox
但它总是空的。
UPDATE 进一步测试后,我知道只有当我为整个DGV使用数据源时才会出现问题。
它工作正常,如果我只需要创建一个列自己:
var test = new DataGridViewTextBoxColumn();
test.Name = "asd";
dataGridView1.Columns.Add(test);
dataGridView1.Rows.Add(new DataGridViewRow());
var cmb = new DataGridViewComboBoxColumn();
cmb.Name = "ComboCol";
cmb.HeaderText = "ComboCol";
dataGridView1.Columns.Add(cmb);
UpdateDataSourceCombo(); //Same function as the original post
我的原代码与数据表到电网的负载的样本更新。
它在这里工作得很好。请注意,下拉列表填充后,除非cell.Value在项目列表中,否则不会显示值!另外:您需要在设置项目的数据源之前设置DGV数据源。顺便说一句,为什么'我
TaW
不确定更新的内容。在每次设置DGV.DataSource之后,您需要设置ITems,这很有意义,因为您希望每个数据都具有行依赖的数据列表。 – TaW