每个单元格具有不同数据源的 DataGridView 组合框 [英] DataGridView comboBox with different dataSources for each cell

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

问题描述

我正在尝试创建一个保存配置信息的 DataGridView.

I am trying to create a DataGridView that holds configuration information.

列中每一行的可用值可以根据不同列中的值进行更改,因此我无法将单个数据源附加到组合框列.例如:如果您选择汽车,可用颜色应仅限于该型号可用的颜色.

The available values can change for each row within a column based on the values in a different column so I can't attach a single datasource to the comboBox column. As an example: If you select car, the availalbe colors should be limited to colors available for that model.

Car                 ColorsAvailable
Camry               {white,black}
CRV                 {white,black}
Pilot               {silver,sage}

考虑使用 dataGridView 的原因是操作员可以为额外的汽车添加行.

The reason for considering the dataGridView is so that the operator can add rows for additional cars.

实现这种类型的 UI 的好设计是什么?

What is a good design to implement this type of a UI?

推荐答案

您可以在每个DataGridViewComboBoxCell上分别设置DataSource:

You can set the DataSource separately on each DataGridViewComboBoxCell:

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0) // presuming "car" in first column
    { // presuming "ColorsAvailable" in second column
        var cbCell = dataGridView1.Rows[e.RowIndex].Cells[1] as DataGridViewComboBoxCell;
        string[] colors = { "white", "black" };
        switch (dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString())
        {
            case "Pilot": colors = new string[] { "silver", "sage" }; break;
                // case "other": add other colors
        }

        cbCell.DataSource = colors;
    }
}

如果您的颜色(甚至可能是汽车)是像枚举数这样的强类型,您当然应该使用这些类型而不是我正在打开并在此处插入的字符串...

If your colors (and maybe even cars) are strong types like enumerators of course you should use those types instead of the strings I'm switching on and inserting here...

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

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