DataGridView comboBox with different dataSources f

2019-01-29 03:51发布

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}

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

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

1条回答
可以哭但决不认输i
2楼-- · 2019-01-29 04:35

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...

查看更多
登录 后发表回答