Search code examples
c#comboboxverification

prevent duplicate selections between multiple comboBoxes


I have a groupBox in my WinForms application. There are about 25 comboBoxes in this groupBox for selecting various options/settings. They all share the same item collection (dropdown items). They are by default all set to different items (no 2 comboBoxes have the same text).

However the customizable nature of my app allows for the user to change a setting to something else. What I want to do is when the user changes the selection index of comboBoxSA to say 3 and there's another comboBox that is already selecting 3 (this will would result in 2 comboBoxes displaying the same text) to flag the user somehow saying that setting cannot be duplicated.

This can happen immediately when the user changes the selectionIndex, when the user tries to close the form, whatever. The only way I can see implementing this right now is having a different selectionIndex changed function for each comboBox and comparing that comboBox's text to every single one of the other comboBoxes.

Any ideas on shortening this up?


Solution

  • This is what I did:

    Created a comboBox List:

    List<ComboBox> toolParameterComboBoxes = new List<ComboBox>();

    Added all the comboBoxes to that list:

    toolParameterComboBoxes.Add(countcomboBox); (Repeated...)

    Changed the selectionIndexChanged event for all the comboBoxes to use this:

    private void validateComboBox(object sender, EventArgs e)
    {
      ComboBox thisCB = sender as ComboBox;
      if (thisCB.Text != "")
      {
           foreach (ComboBox cb in toolParameterComboBoxes)
           {
               if (thisCB.Name != cb.Name && thisCB.Text == cb.Text && thisCB.Text != "" && cb.Text != "")
               {
                   MessageBox.Show("You cannot duplicate tool parameters." + "\r\n" + "\r\n" 
                                + "That option has been selected in " + cb.Name.Replace("comboBox", ""), "Error");
                            thisCB.SelectedIndex = 0;
                            break;
               }
            }
      }
    }
    

    This handles comboBoxes that are empty. For some reason thisCB.Text = ""; didn't work, so I added a empty comboBox item to each of their collection and simply changed the selected index to 0 so a duplicate item could never be selected.