如何在每个单元格中设置具有不同数据源的 DataGridView ComboBoxColumn? [英] How do I set up a DataGridView ComboBoxColumn with a different DataSource in each cell?

查看:32
本文介绍了如何在每个单元格中设置具有不同数据源的 DataGridView ComboBoxColumn?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在像这样设置 DataGridViewComboBoxColumn:

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

这是有效的:每一行在该列中都有一个下拉框,填充有 a、b、c.

This works: each row has a dropdown box in that column, populated with 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" };                        
}

然而,这段代码没有效果——每一行仍然显示a"、b"、c".

However, this code has no effect - every row still shows "a", "b", "c".

我尝试用 new Listnew BindingList 替换 new string[],但都无济于事.

I have tried replacing new string[] with new List<string> and new BindingList<string>, both to no avail.

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

I also have tried removing the code that sets newColumn.DataSource, but then the lists are empty.

我应该如何正确执行此操作?

How should I go about doing this properly?

推荐答案

以下对我有用:

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" };
}

这篇关于如何在每个单元格中设置具有不同数据源的 DataGridView ComboBoxColumn?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆