SelectedIndexChanged event in ComboBoxColumn in Datagridview

I want to handle this "SelectedIndexChanged" event in a DataGridViewComboBoxColumn, and I set it to the "EditingControlShowing" gridview event.

Problem: The "SelectedIndexChanged" event does not fire on the first attempt to select an item from comboBox, but after selecting this item a second time, the event fires and everything works fine!

Here is the code:

private void dgvRequest_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { ComboBox combo = e.Control as ComboBox; if (combo != null) { if (dgvRequest.CurrentCell.ColumnIndex == col_ConfirmCmb.Index) { combo.SelectedIndexChanged -= combo_ConfirmSelectionChange; combo.SelectedIndexChanged += combo_ConfirmSelectionChange; return; } } } void combo_ConfirmSelectionChange(object sender, EventArgs e) { if (dgvRequest.CurrentCell.ColumnIndex != col_ConfirmCmb.Index) return; ComboBox combo = sender as ComboBox; if (combo == null) return; MessageBox.Show(combo.SelectedText);// returns Null for the first time } 
+2
source share
1 answer

Everything gets complicated as they optimized the DataGridView with only one edit control for all rows. Here's how I dealt with a similar situation:

First connect the delegate to the EditControlShowing event:

 myGrid.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler( Grid_EditingControlShowing); ... 

Then in the handler, connect to the EditControl SelectedValueChanged event:

 void Grid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { ComboBox combo = e.Control as ComboBox; if (combo != null) { // the event to handle combo changes EventHandler comboDelegate = new EventHandler( (cbSender, args) => { DoSomeStuff(); }); // register the event with the editing control combo.SelectedValueChanged += comboDelegate; // since we don't want to add this event multiple times, when the // editing control is hidden, we must remove the handler we added. EventHandler visibilityDelegate = null; visibilityDelegate = new EventHandler( (visSender, args) => { // remove the handlers when the editing control is // no longer visible. if ((visSender as Control).Visible == false) { combo.SelectedValueChanged -= comboDelegate; visSender.VisibleChanged -= visibilityDelegate; } }); (sender as DataGridView).EditingControl.VisibleChanged += visibilityDelegate; } } 
+5
source

Source: https://habr.com/ru/post/1368991/


All Articles