How to populate each DataGridViewComboBoxCell with different data?

戏子无情 提交于 2020-12-06 02:58:50

问题


i have two DataGridViewComboBoxColumn that i add at run time i need the items of the first DataGridViewComboBoxColumn to stay the same in all the rows of the gridview but i want the items of the second DataGridViewComboBoxColumn to be different from row to the other depending on the selected item of the first DataGridViewComboBoxColumn

if we say the first DataGridViewComboBoxColumn represents the locations and the second DataGridViewComboBoxColumn to represent the sublocations. so i want the second DataGridViewComboBoxColumn items to be the sublocations of the selected location from the first DataGridViewComboBoxColumn


回答1:


One option is to change the datasource at cell level for sublocations.

Supposing the grid is named grid and the two grid columns were named locationsColumn respectively subLocationsColumn:

private void Form1_Load(object sender, EventArgs e)
{
    locationsColumn.DataSource = new string[] { "Location A", "Location B" };
}

then, on grid's CellEndEdit event:

private void grid_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    if(locationsColumn.Index == e.ColumnIndex)
    {
        DataGridViewComboBoxCell subLocationCell = 
            (DataGridViewComboBoxCell)(grid.Rows[e.RowIndex].Cells["subLocationsColumn"]);

        string location = grid[e.ColumnIndex, e.RowIndex].Value as String;

        switch (location)
        {
            case "Location A":
                subLocationCell.DataSource = new string[] {
                    "A sublocation 1",
                    "A sublocation 2",
                    "A sublocation 3" 
                };
                break;
            case "Location B":
                subLocationCell.DataSource = new string[] { 
                    "B sublocation 1",
                    "B sublocation 2",
                    "B sublocation 3" 
                };
                break;
            default:
                subLocationCell.DataSource = null;
                return;
        }
    }
}

Some additional handling is necessary when the location changes for existing rows but this is the basic idea.




回答2:


Check this out, I think it outlines what you need:

http://www.timvw.be/2007/01/17/exploring-datagridviewcomboboxcolumn-databinding/




回答3:


One idea would be to use a secondary Binding Source for the "SubLocations" column. This BindingSource can be filtered by the LocationId selected in the "Locations" column. The key to do this is to use the EditingControlShowing and CellValueChanged events of the grid to set the proper filtering on the SubLocations column when the selected Location changes.

There is one example here.



来源:https://stackoverflow.com/questions/446600/how-to-populate-each-datagridviewcomboboxcell-with-different-data

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