This is a cod. to populate a combobox with a list that will populate through the insert event that will retrieve a value from a textbox, and will cause the selected name in combobox1 not to appear in combobox 2 and so on respectively.
I'm having an error in the insert. Where the following error message appears:
An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dllAdditional information: Collection has been modified; the enumeration operation may not be performed.
//arrays
public List<ComboBox> combos;
public List<string> originalSource = new List<string> {"Nome1", "Nome2"};
public List<object> selectedItems = new List<object>();
//############################ ---Errrrro --- #########################
private void inserir_Click(object sender, EventArgs e)
{
foreach (var item in originalSource)
{
String _Temp = "";
_Temp = textBox1.Text.ToString();
originalSource.Add(_Temp);
}
}
//povoar combos
private void InitializeCombos()
{
combos = new List<ComboBox> { comboBox1, comboBox2, comboBox3 };
combos.ForEach(combo =>
{
originalSource.ForEach(item => combo.Items.Add(item));
combo.SelectedIndexChanged += RemoveOptionFromCombo;
});
}
//Remover intens duplicados
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);
});
});
}
Note: The error only appears when triggering the event.