Suppose, I have this DataGridView
in my application.
- Child
is a combo-box column
- ChildID
is a combo-box column
I have some objects named Table
which I want to load in the Child
-column. Each Table
object has a number of Column
objects which I want load in ChildID
-column.
When I change a Child
combo box, ChildID
column should automatically change to load appropriate columns from the Table
object.
The following code is my attempt:
// 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();
}
}
But, it doesn't work.