2009-07-07 131 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事件。然後,可以基於該行的內容以編程方式設置組合框中的內容。

當然,這假定您正在將數據綁定到網格。

相關問題