我有一個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