I have DataGridView
which contains two ComboBox
columns.
The second ComboBox
will be filled with data depending on the selected value from first ComboBox
.
How to handle the SelectedIndexChanged
event for the first ComboBox
.
If I use EditingControlShowing
event then cb_SelectedIndexChanged
fires several times, even when user selects combobox but doesn't change selection.
This works for me:
private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == comboboxColumn.Index && e.RowIndex >= 0) //check if combobox column
{
object selectedValue = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
}
}
//changes must be committed as soon as the user changes the drop down box
private void dataGridView1_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty)
{
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
}
A great resource for DataGridView questions can be found here:
http://www.windowsclient.net/Samples/Go%20To%20Market/DataGridView/DataGridView%20FAQ.doc
From there on how to handle a selected change event:
How do I handle the SelectedIndexChanged event?
Sometimes it is helpful to know when a user has selected an item in the ComboBox editing control. With a ComboBox on your form you would normally handle the SelectedIndexChanged event. With the DataGridViewComboBox you can do the same thing by using the DataGridView.EditingControlShowing event. The following code example demonstrates how to do this. Note that the sample also demonstrates how to keep multiple SelectedIndexChanged events from firing.
private void dataGridView1_EditingControlShowing(object sender,
DataGridViewEditingControlShowingEventArgs e)
{
ComboBox cb = e.Control as ComboBox;
if (cb != null)
{
// first remove event handler to keep from attaching multiple:
cb.SelectedIndexChanged -= new
EventHandler(cb_SelectedIndexChanged);
// now attach the event handler
cb.SelectedIndexChanged += new
EventHandler(cb_SelectedIndexChanged);
}
}
void cb_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show("Selected index changed");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With