DataGridView comboBox with different dataSources for each cell

烂漫一生 提交于 2019-12-18 07:16:06

问题


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:


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



来源:https://stackoverflow.com/questions/9162744/datagridview-combobox-with-different-datasources-for-each-cell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!