ComboBox column in DataGridView - getting immediate feedback when selection is changed

0
0

I have a DataGridView, within which I have a DataGridViewComboBoxColumn.  I’d like to get notification (an event) immediately when the user changes the selection.

Normal DGV behavior is to delay committing edits until after cell exit.  This means I don’t get any event until after the user does something (click, keystroke) after the edit – this is one click “too late”.

I have a solution, but it’s messy –

  • Set the DVG EditMode property to EditOnEnter.
  • Set the ComboBoxColumn DropDownStyle to DropDownList
  • In the handler for EditControlShowing, determine if I’m on the combo box column and if so, fish out the DataGridViewComboBoxEditingControl and save it in a field of my page class.
  • Hook the SelectedItemChanged event on that control and in the handler for that event, implement my intended action.
  • In the handler for CellEndEdit, unhook the event handler from the edit control & forget the control.
    • … being careful to deal with all of the cases to prevent hooking the event multiple times or holding onto a reference to a no longer relevant control.

It works, but is there a better way?

 

  • You must to post comments
0
0

Yes, there is a better way.
Use EditingControlShowing (e.Control is the ComboBox).

In the handler simply do:
((ComboBox)e.Control).SelectedIndexChanged -= ...
and ((ComboBox)e.Control).SelectedIndexChanged += ...

Doing always -= and += ensures that there is only one handler attached.

 

Alternatively, you could create a custom column and override OnSelectedItemChanged in DataGridViewComboBoxEditingControl.

  • Carl Daniel
    Equivalent, more or less.
  • You must to post comments
Showing 1 result
Your Answer

Please first to submit.