【问题标题】:How do I set up a DataGridView ComboBoxColumn with a different DataSource in each cell?如何在每个单元格中设置具有不同数据源的 DataGridView ComboBoxColumn?
【发布时间】:2009-07-07 00:51:54
【问题描述】:

我正在像这样设置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>,均无济于事。

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

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

【问题讨论】:

    标签: c# .net datagridview


    【解决方案1】:

    以下对我有用:

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

    【讨论】:

    • 嗯,这也适用于我 - 在一个干净的测试项目中。这一定是我在做不同的事情..
    • 好的,问题与我的 DataGridView 将 AutoSizeColumnMode 设置为 AllCells 的事实有关。我认为这是在设置数据源(或其他东西)之前验证单元格的值。
    【解决方案2】:

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

    当然,这假定您正在对网格进行数据绑定。

    【讨论】:

    • 我是数据绑定,但这是winforms,不是web。 winforms datagridview 似乎没有这个事件..
    猜你喜欢
    • 2012-02-28
    • 2015-01-27
    • 2020-02-15
    • 2018-07-05
    • 1970-01-01
    • 2018-04-15
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    相关资源
    最近更新 更多