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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With