[Flags]
//This is the enum of column list in the dataGridView.
private enum Column
{
ParentCombo,
ChildCombo
}
private string oldValue = null;
private string newValue = null;
private void Form_Load(object sender, EventArgs e)
{
#region Set the DataSource of Column: Parent ComboBox
ColumnParent.DataSource = GetParentDT();
ColumnParent.DisplayMember = "YourDisplayMember";
ColumnParent.ValueMember = "YourValueMember";
#endregion
#region Fill the dataGridView
using (SqlConnection sqlConn = GetYourSQLconn())
{
SqlCommand sqlComm = new SqlCommand(storedProcedure, sqlConn);
sqlComm.CommandType = CommandType.StoredProcedure;
sqlComm.Parameters.AddRange(GetYourSQLparameters());
using (SqlDataReader dataReader = sqlComm.ExecuteReader())
{
dataGridView.Rows.Clear();
while (dataReader.Read())
{
dataGridView.Rows.Add();
for (int colIndex = 0; colIndex < dataReader.FieldCount; colIndex++)
{
dataGridView[colIndex, dataGridView.RowCount - 1].Value = dataReader[colIndex];
}
}
}
}
#endregion
}
private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
#region Set the DataSource of Child ComboBox According to Parent ComboBox Value
if (e.ColumnIndex == (int)Column.ParentCombo)
{
(dataGridView[(int)Column.ChildCombo, e.RowIndex] as DataGridViewComboBoxCell).DataSource = GetChildDT(e.RowIndex);
(dataGridView[(int)Column.ChildCombo, e.RowIndex] as DataGridViewComboBoxCell).DisplayMember = "YourDisplayMember";
(dataGridView[(int)Column.ChildCombo, e.RowIndex] as DataGridViewComboBoxCell).ValueMember = "YourValueMember";
}
#endregion
}
#region Clear Child ComboBox Selection on Parent ComboBox Value Changed
private void dataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
oldValue = dataGridView[(int)Column.ParentCombo, e.RowIndex].Value.ToString();
}
private void dataGridView_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
newValue = dataGridView[(int)Column.Problem, e.RowIndex].Value.ToString();
if (newValue != oldValue)
{
dataGridView[(int)Column.ChildCombo, e.RowIndex].Value = null;
}
}
#endregion
...
Please note that I set my dataGridView to:
- Enable Adding = false;
- Enable Editing = true;
- Enable Deleting = false;
I provided some buttons for Add/Edit/Delete though (unseen in this code).
No comments:
Post a Comment