Error povoar combobox - An unhandled Exception of type 'System.Invalidoperationexception' occurred in mscorlib.dll

Asked

Viewed 1,220 times

0

This is a Cod. to fill a combobox with a list that will be populated by the insert event that will redeem a value from a textbox, and will cause the name selected in combobox1 not to appear in combobox 2 and so on respectively.

I have an error inserting. Where the following error message appears :

An unhandled Exception of type 'System.Invalidoperationexception' occurred in mscorlib.dll

Additional information: Collection has been modified; perhaps the enumeration operation will 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.

2 answers

4


You cannot 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);
}
  • Bernardo the error persists. See more: [http://www.sendspace.com/file/5mq3qo]

  • I downloaded your application. What happens now is an infinite iteration, since for each item in the list, a new item is added. For the new item added, a new item is added, and so on, infinitely. This is a logic error. To solve, it is necessary to understand exactly what the purpose of the code is.

  • There really was a logic error, I modified: private void inserir_Click(object sender, EventArgse) { originalSource.Add(textBox1.Text.ToString()); } The goal and when the click event is triggered it adds what was in the texbox in the list and then can combobox with what is inside it The error is now found in another location as new items do not appear in combobox’s

0

Follow the answer 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
  • You seem to be having trouble formatting, check out http://answall.com/editing-help. It’s nice to also explain because your code solves the problem, see [Answer]. In fact, it seems that the comment you made in Bernardo’s reply is the explanation and lack in this answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.