一种选择是在单元级别更改子位置的数据源。
假设网格被命名grid
并且两个网格列分别被locationsColumn
命名subLocationsColumn
:
private void Form1_Load(object sender, EventArgs e)
{
locationsColumn.DataSource = new string[] { "Location A", "Location B" };
}
然后,在网格CellEndEdit
事件中:
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;
}
}
}
当现有行的位置发生变化时,需要进行一些额外的处理,但这是基本思想。