假设我的申请中有DataGridView
- Child
是一个组合框列
- ChildID
是一个组合框列
我有一些名为Table
的对象,我想在Child
- 列中加载。每个Table
对象都有一些Column
个对象,我想在ChildID
- 列中加载。
当我更改Child
组合框时,ChildID
列应自动更改为从Table
对象加载相应的列。
以下代码是我的尝试:
// populate the DataGridView
if (database != null)
{
childDataGridView1Column1.Items.Clear();
dataGridView1.Rows.Clear();
string firstTableName = database.Tables[0].Name;
// Loading ComboBox columns
int i = 0;
foreach (Table t in database.Tables)
{
dataGridView1.Rows.Add(true, t.Name, t.PrimaryKeyName);//Set Child's text to "None"
dataGridView1.Rows[i].Tag = t;
// Load 'Database.Tables' to 'Child' column
DataGridViewComboBoxCell dataGridview1ChildComboBoxCell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells[(int)CellNo.Child];
dataGridview1ChildComboBoxCell.Items.Clear();
foreach (Table t2 in database.Tables)
{
dataGridview1ChildComboBoxCell.Items.Add(t2.Name);
}
dataGridView1.Rows[i].Cells[(int)CellNo.Child].Value = firstTableName;
// Load 'Table.Columns' to 'ChildID' column
DataGridViewComboBoxCell dataGridview1ChildIDComboBoxCell = (DataGridViewComboBoxCell)dataGridView1.Rows[i].Cells[(int)CellNo.ChildID];
dataGridview1ChildIDComboBoxCell.Items.Clear();
foreach (Column c in t.Columns.Values)
{
dataGridview1ChildIDComboBoxCell.Items.Add(c.Name);
}
i++;
}
}
... ... ...
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
//DataGridViewComboBoxCell cb = (DataGridViewComboBoxCell)dataGridView1.Rows[e.RowIndex].Cells[(int)CellNo.Child];
//if (cb.Value != null)
{
// do stuff
DataGridViewRow row = dataGridView1.SelectedRows[0];
Table t = row.Tag as Table;
// Load 'Table.Columns' to 'ChildID' column
DataGridViewComboBoxCell dataGridview1ChildIDComboBoxCell = (DataGridViewComboBoxCell)row.Cells[(int)CellNo.ChildID];
dataGridview1ChildIDComboBoxCell.Items.Clear();
foreach (Column c in t.Columns.Values)
{
dataGridview1ChildIDComboBoxCell.Items.Add(c.Name);
}
dataGridView1.Invalidate();
}
}
但是,它不起作用。