2009-07-07 42 views
11

我设立一个DataGridViewComboBoxColumn这样的:如何在每个单元格中使用不同的DataSource设置DataGridView ComboBoxColumn?

var newColumn = new DataGridViewComboBoxColumn() { 
    Name = "abc" 
}; 
newColumn.DataSource = new string[] { "a", "b", "c" }; 
dgv.Columns.Add(newColumn); 

此作品:每行有在该列下拉框,填入A,B,C。

但是,现在我想修剪某些行的列表。我想设置每行的列表如下:

foreach (DataGridViewRow row in dgv.Rows) { 
    var cell = (DataGridViewComboBoxCell)(row.Cells["abc"]);   
    cell.DataSource = new string[] { "a", "c" };       
} 

然而,这个代码没有任何影响 - 每行仍显示“A”,“B”,“C”。

我试过用new List<string>new BindingList<string>替代new string[],都无济于事。

我也尝试删除代码,设置newColumn.DataSource,但然后列表是空的。

我应该如何正确地做到这一点?

回答

20

对我来说,以下工作:

DataGridViewComboBoxColumn newColumn = new DataGridViewComboBoxColumn(); 
newColumn.Name = "abc"; 
newColumn.DataSource = new string[] { "a", "b", "c" }; 
dataGridView1.Columns.Add(newColumn); 

foreach (DataGridViewRow row in dataGridView1.Rows) 
{ 
    DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)(row.Cells["abc"]); 
    cell.DataSource = new string[] { "a", "c" }; 
} 

你也可以尝试(这也为我的作品):

for (int row = 0; row < dataGridView1.Rows.Count; row++) 
{ 
    DataGridViewComboBoxCell cell = 
     (DataGridViewComboBoxCell)(dataGridView1.Rows[row].Cells["abc"]); 
    cell.DataSource = new string[] { "f", "g" }; 
} 
+0

嗯,这也适用于我 - 在一个干净的测试项目。它必须是我做不同的事情.. – Blorgbeard 2009-07-07 22:38:51

+3

好吧,问题是与我的DataGridView AutoSizeColumnMode设置为AllCells的事实。我认为它是在数据源设置之前验证单元格的值(或其他)。 – Blorgbeard 2009-07-07 23:49:59

0

另一种选择是尝试的行级数据绑定。尝试使用事件OnRowDataBound事件。然后,可以基于该行的内容以编程方式设置组合框中的内容。

当然,这假定您正在将数据绑定到网格。

相关问题