Error populating combobox - An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll

0

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.dll

     

Additional 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.

    
asked by anonymous 21.05.2014 / 01:15

2 answers

4

You can not modify a collection within an iteration foreach .

Use an iteration for .

for(int i = 0; i < originalSource.Count; i++)
{
    String _Temp = "";
    _Temp = textBox1.Text.ToString();
    originalSource.Add(_Temp);
}
    
21.05.2014 / 02:23
0

Follow the response code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ExemploLista  
{
public partial class Form1 : Form
{
    private List<string> pessoas = new List<string>();

    public Form1()
    {
        InitializeComponent();

        for (int i = 1; i < 4; i++)
        { pessoas.Add(string.Format("Valor {0}", i)); }

        this.InitializeControls();
    }

    private void InitializeControls(ComboBox control = null)
    {
        List<string> dataSource = this.FilterData();

        foreach (Control item in this.Controls)
        {
            if (item is ComboBox )
            {
                if ((ComboBox)item != control)
                {
                    this.PopulateControl((ComboBox)item, dataSource);
                }
                else
                {
                    this.PopulateControl((ComboBox)item, dataSource, control.Text);
                }
            }

        }
    }

    private List<string> FilterData()
    {
        List<string> usedValues = new List<string>();
        foreach (Control item in this.Controls)
        {
            if (item is ComboBox)
            {
                if (!string.IsNullOrEmpty(((ComboBox)item).Text))
                { usedValues.Add(((ComboBox)item).Text); }
            }
        }

        var result = from s in this.pessoas
                     where !usedValues.Contains(s)
                     select s;

        return result.ToList();
    }

    private void PopulateControl(ComboBox control, List<string> datasource, string text = null)
    {
        if (!string.IsNullOrEmpty(text))
        {
            foreach (var item in datasource)
            {
                if (item != text && control.Items.IndexOf(item) == -1)
                {
                    control.Items.Add(item);
                }
            }
        }
        else
        { 
            control.Items.Clear();
            foreach (var item in datasource)
            { 
                control.Items.Add(item); 
            }
        }
    }

    private void CombomBoxSelectedIndexChanged(object sender, EventArgs e)
    {
        this.InitializeControls((ComboBox)sender);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.pessoas.Add(textBox1.Text);
        this.InitializeControls();
        textBox1.Clear();
    }

}
}

#endregion
    
29.05.2014 / 01:58