Search code examples
c#comboboxselectedindexchanged

two combobox firing an event for same function


There are two comboboxes. one is created by drag&drop and set event SelectedIndexChanged. And 2nd combobox is created manually, but not given any event. But when I change 2nd combo, it's firing an event for 1st combo's function.

Form prompt = new Form();
prompt.Width = 300;
prompt.Height = 150;

    ComboBox cmBox = new ComboBox() { Left = 70, Top = 24, Width = 100, Height=150 };
    cmBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
    cmBox.ValueMember = "value";
    cmBox.DisplayMember = "text";

prompt.ShowDialog();

I tried, but not working:

cmBox.SelectedIndexChanged -= new System.EventHandler(comboBox1_SelectedIndexChanged);

P.S: They are using same bindsource.


Solution

  • If they're sharing a BindingSource, then changing the value in one control will change the value in the other control as well.

    When you change the value in the second ComboBox, the value in the first ComboBox changes too, which fires its SelectedIndexChanged event.

    Create a separate BindingSource for each control, or if it's a collection, try just assigning the collection directly to each ComboBox.