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);
});
});
}
}