How to remove the selected option in multiple ComboBoxes?

3

I have several components of type ComboBox with identical options. The user must select one of them (eg "Name"). How do I make an option in any of the ComboBox , it disappear from all ComboBox ?

Do I need a bank? Or a IList ?

    
asked by anonymous 13.03.2014 / 21:18

2 answers

2

Assuming you have three combos in your form with the names of comboBox1 , comboBox2 , comboBox3 . See if the code below will answer you. Notice that in the example I do not use DataSource of combos and so I have the freedom to change their Items .

public partial class Form1 : Form
{
    private List<ComboBox> _combos;
    private List<string> _originalSource = new List<string> { "um", "dois", "três", "quatro", "cinco" };
    private List<object> _selectedItems = new List<object>();

    public Form1()
    {
        InitializeComponent();
        InitializeCombos();
    }

    private void InitializeCombos()
    {
        _combos = new List<ComboBox> { comboBox1, comboBox2, comboBox3 };
        _combos.ForEach(combo =>
        {
            _originalSource.ForEach(item => combo.Items.Add(item));
            combo.SelectedIndexChanged += RemoveOptionFromCombo;
        });
    }

    private void RemoveOptionFromCombo(object sender, EventArgs e)
    {
        var selectedItem = ((ComboBox)sender).SelectedItem;
        _selectedItems = new List<object> 
        {
            comboBox1.SelectedItem, comboBox2.SelectedItem, comboBox3.SelectedItem
        };

        _combos.ForEach(combo =>
        {
            _originalSource.ForEach(item =>
            {
                if (!combo.Items.Contains(item) && !_selectedItems.Contains(item))
                    combo.Items.Add(item);
                if (combo.Items.Contains(item) && _selectedItems.Contains(item) && !item.Equals(combo.SelectedItem))
                    combo.Items.Remove(item);
            });
        });
    }
}
    
18.03.2014 / 23:27
2

One simple way to do this is by setting the values you need in an array and looping repetitively to populate the combobox.

You can do this in the event ComboBox.SelectedIndexChanged it:

  • Clean the other combobox using ComboBox.Items.Clear () - or only where it is duplicated according to your need.
  • Run a new loopback to populate the combobox that test and do not include the already selected item.
18.03.2014 / 15:33