Nurdism
Nurdism

Reputation: 608

C# CheckedListBox InvalidOperationException on a foreach loop

I Don't know what I'm doing wrong but I keep getting this error. Does anyone know what could be causing this?

InvalidOperationException List that this enumerator is bound to has been modified. An enumerator can only be used if the list does not change.

    public static string[] WRD = new string[] {"One","Two","Three","Four"}

    public static string[] SYM = new string[] {"1","2","3","4"}

    //this is how I'm populating the CheckedListBox
    private void TMSelectionCombo_SelectedIndexChanged(object sender, EventArgs e)
    {
        TMSelection.Items.Clear();
        switch (TMSelectionCombo.SelectedItem.ToString())
        {
            case "Words":
                foreach (string s in WRD)
                {
                    TMSelection.Items.Add(s);
                }
                break;
            case "Symbols":
                foreach (string s in SYM)
                {
                    TMSelection.Items.Add(s);
                }
                break;
        }
    }

    //this is where the problem is
    private void AddTMs_Click(object sender, EventArgs e)
    {
        //on this first foreach the error is poping up
        foreach (Object Obj in TMSelection.CheckedItems)
        {
            bool add = true;
            foreach (Object Obj2 in SelectedTMs.Items)
            {
                if (Obj == Obj2)
                    add = false;
            }
            if (add == true)
                TMSelection.Items.Add(Obj);
        }
    }

Upvotes: 1

Views: 1711

Answers (2)

craig1231
craig1231

Reputation: 3877

You cannot change the items in the TMSelection enumeration.

Example

List<string> myList = new List<string>();

foreach (string a in myList)
{
    if (a == "secretstring")
        myList.Remove("secretstring");    // Would throw an exception because the list is being enumerated by the foreach
}

To resolve this, use a temporary list.

Example

List<string> myList = new List<string>();
List<string> myTempList = new List<string>();

// Add the item to a temporary list
foreach (string a in myList)
{
    if (a == "secretstring")
        myTempList.Add("secretstring");
}

// To remove the string
foreach (string a in myTempList)
{
    myList.Remove(a);
}

So in your exmaple, add the new items to a temporary list, then after the foreach loop add each item to the main list.

Upvotes: 1

Paul Nikonowicz
Paul Nikonowicz

Reputation: 3903

An enumerator can only be used if the list does not change.

Yup

Create another list of what you want to add and then join that list with the list you want to modify.

Like this:

List toAdd = new List()
for(Object item in list) {
     if(whatever) {
         toAdd.add(item);
     }
}
list.addAll(toAdd);

Upvotes: 1

Related Questions