How to stop selection change event in combo-box from firing when populating loading it

If you have ever wanted to take some action when a user changes a selection in a combo-box (drop down selection list) you would put your code in the SelectionChanged event of the WinForm or WPF system. If you have ever wanted to set the combo-box to a default value when the window is being created, then you have probably experienced what this article is about. When you set the combo-box to a default value, the SelectionChanged event is fired. In a majority of the cases you do not want this to happen because, 1. it’s not being triggered by a user action and 2. it will execute the logic in your SelectionChanged event, probably unnecessarily, increasing startup/rendering time. What I do to get around this is detach and then reattach the event before and after the default value is set. This is also referred to as “wiring up” and event.

[sourcecode language="csharp" padlinenumbers="true" autolinks="false" gutter="false" toolbar="false"]
private void comboBox1_SelectionChanged(object sender, 
                                SelectionChangedEventArgs e)
   MessageBox.Show("comboBox1_SelectionChanged event called", 
                   "Event", MessageBoxButton.OK, 
   //Add your other logic here....

Above is the method that gets triggered when the user changes the value or the program changes the value in the combo-box. For this example I display a message box. Below is the logic that loads 2 strings into a LIST and then populates the the combo-box with the LIST. Just a simple example, in a real system you would probably do a data bind with a result set from the database.

[sourcecode language="csharp" autolinks="false" gutter="false" toolbar="false"]
public void PopulateAssemblyComboBox()
   List<string> comboBoxList = new List<string>();
   comboBoxList.Add("Some Date"); 
   comboBoxList.Add("Default Data");           
   comboBox1.ItemsSource = comboBoxList;
   comboBox1.SelectionChanged -= 
      new SelectionChangedEventHandler(comboBox1_SelectionChanged);
   comboBox1.Text = "Default Data";
   comboBox1.SelectionChanged += 
      new SelectionChangedEventHandler(comboBox1_SelectionChanged);

You will see that I bind the comboboxList to the ItemsSource of the comboBox, then I de-attach the SelectionChanged event from the comboBox, set the default value and then rewire the event to the comboBox. I need to rewire it so that when a user changes the value the SelectionChanged event is triggered and what is coded in the event is executed.

Leave a Comment

Your email address will not be published.