Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView comboBox with different dataSources for each cell

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?

like image 628
DarwinIcesurfer Avatar asked Nov 07 '25 08:11

DarwinIcesurfer


1 Answers

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

like image 172
Chuck Wilbur Avatar answered Nov 09 '25 10:11

Chuck Wilbur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!