C# 如何在每个单元格中设置具有不同数据源的 DataGridView ComboBoxColumn?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1089889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I set up a DataGridView ComboBoxColumn with a different DataSource in each cell?
提问by Blorgbeard is out
I am setting up a DataGridViewComboBoxColumn
like this:
我正在设置一个DataGridViewComboBoxColumn
这样的:
var newColumn = new DataGridViewComboBoxColumn() {
Name = "abc"
};
newColumn.DataSource = new string[] { "a", "b", "c" };
dgv.Columns.Add(newColumn);
This works: each row has a dropdown box in that column, populated with a, b, c.
这是有效的:每一行在该列中都有一个下拉框,填充有 a、b、c。
However, now I would like to trim the list for certain rows. I'm trying to set the list per row like this:
但是,现在我想修剪某些行的列表。我正在尝试像这样设置每行列表:
foreach (DataGridViewRow row in dgv.Rows) {
var cell = (DataGridViewComboBoxCell)(row.Cells["abc"]);
cell.DataSource = new string[] { "a", "c" };
}
However, this code has no effect - every row still shows "a", "b", "c".
但是,此代码无效 - 每行仍显示“a”、“b”、“c”。
I have tried replacing new string[]
with new List<string>
and new BindingList<string>
, both to no avail.
我曾尝试更换new string[]
同new List<string>
和new BindingList<string>
,都无济于事。
I also have tried removing the code that sets newColumn.DataSource
, but then the lists are empty.
我也尝试删除设置的代码newColumn.DataSource
,但列表是空的。
How should I go about doing this properly?
我应该如何正确地做到这一点?
采纳答案by SwDevMan81
The following works for me:
以下对我有用:
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" };
}
You could also try (this also works for me):
您也可以尝试(这也适用于我):
for (int row = 0; row < dataGridView1.Rows.Count; row++)
{
DataGridViewComboBoxCell cell =
(DataGridViewComboBoxCell)(dataGridView1.Rows[row].Cells["abc"]);
cell.DataSource = new string[] { "f", "g" };
}
回答by Andy_Vulhop
Another option is to try databinding on the row level. Try using the event OnRowDataBound event. Then you can programatically set what is in the combo box based on the contents of that row.
另一种选择是尝试在行级别进行数据绑定。尝试使用事件 OnRowDataBound 事件。然后,您可以根据该行的内容以编程方式设置组合框中的内容。
Of course, this presumes you are databinding you grid.
当然,这假定您正在对网格进行数据绑定。