如何填充每个DataGridViewComboBoxCell不同的数据? [英] How to populate each DataGridViewComboBoxCell with different data?
问题描述
我有两个DataGridViewComboBoxColumn,我添加在运行时,我需要的第一个DataGridViewComboBoxColumn的项目在gridview的所有行保持不变,但我想要的第二个DataGridViewComboBoxColumn的项目是不同的行到其他依赖如果我们说第一个DataGridViewComboBoxColumn表示位置,并且第二个DataGridViewComboBoxColumn表示子位置,则在第一个DataGridViewComboBoxColumn
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
所以我想要第二个DataGridViewComboBoxColumn项目是从第一个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
推荐答案
假设网格被命名为 grid
,并且两个网格列被命名为 locationsColumn
subLocationsColumn
:
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" };
}
然后,在grid的 CellEndEdit
event:
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.
这篇关于如何填充每个DataGridViewComboBoxCell不同的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!