[英]How do I set up a DataGridView ComboBoxColumn with a different DataSource in each cell?
我正在像這樣設置一個DataGridViewComboBoxColumn
:
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 string[]
new List<string>
和new BindingList<string>
替換new string[]
,但都無濟於事。
我也嘗試刪除設置newColumn.DataSource
的代碼,但是列表為空。
我應該如何正確地做到這一點?
以下對我有用:
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" };
}
另一種選擇是嘗試在行級別進行數據綁定。 嘗試使用事件OnRowDataBound事件。 然后,您可以根據該行的內容以編程方式設置組合框中的內容。
當然,這假定您要對網格進行數據綁定。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.