Windows Forms how to find out if selectedindex was changed by user or by code

Can you use the SelectionChangeCommitted event instead?

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

EDIT: The SelectionChangeCommitted event has a major failing: if you use F4 to drop down the list then mouse over your selection and use the Tab key to go to the next control, it does not fire.

There's a [closed and deleted] bug on Connect about it, which suggests using the DropDownClosed event as well to catch this edge case.


I've gotten stuck in situations before where a UI change propagates to the Model, then the Model change propagates back to the UI and it creates an endless cycle. Are you dealing with something like that?

If so, one way out is to only update the UI from the model only if they differ. That is:

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

If that doesn't get 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;
    ...
}

Tags:

C#

.Net

Winforms