Windows Forms, how to find out if selectedindex has been modified by user or code

I have a combobox in a Windows Forms project with an event related event modified by selectedindex. The event is fired when the selected index changes both from the code and from user input. How do you determine if a selected indexex changes due to user input?

+4
source share
4 answers

Can you use the SelectionChangeCommitted event?

SelectionChangeCommitted is raised only when the user changes the selection of the combo box

EDIT: the SelectionChangeCommitted event has serious glitches: if you use F4 to drop a list, then hover over your choice and use the Tab key to go to the next control, it does not fire.

It has a [closed and deleted] Connect error, which suggests using the DropDownClosed event to catch this cormer case.

+8
source

I got stuck in situations before the user interface in the Model changes, then the model change extends to the user interface and creates an endless loop. Are you dealing with something like that?

If so, then the only way out is to update the user interface from the model only if they differ. I.e:

 if (comboBox.SelectedItem != newValue) comboBox.SelectedItem = newValue; 

If this does not give you what you want, another option is to temporarily remove the event handler:

 comboBox.SelectedIndexChanged -= this.comboBox_SelectedIndexChanged; comboBox.SelectedIndex = newIndex; comboBox.SelectedIndexChanged += this.comboBox_SelectedIndexChanged; 

or, instruct the handler to ignore this event:

 ignoreComboBoxEvents = true; comboBox.SelectedIndex = newIndex; ignoreComboBoxEvents = false; ... public void comboBox_SelectedIndexChanged(object sender, EventArgs e) { if (ignoreComboBoxEvents) return; ... } 
+5
source

The event handler is called only after user input, and not after changing the index code. Either handle this case, or set the Boolean flag there, saying that it was entered by the user, so that another part of the code can see that the last index change occurred due to user input.

0
source

You can set a logical flag whenever the selected index is changed by code, and the handler can interrupt (reset the flag) whenever this flag is set.

0
source

All Articles