在foreach循环上的C#CheckedListBox InvalidOperationException

时间:2012-02-14 21:53:24

标签: c# .net

我不知道我做错了什么,但我一直收到这个错误。有谁知道这可能导致什么?

出现InvalidOperationException 已修改此枚举器绑定的列表。 只有在列表没有更改时才能使用枚举器。

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

2 个答案:

答案 0 :(得分:1)

  

只有在列表不变的情况下才能使用枚举器。

创建另一个要添加的列表,然后将该列表与要修改的列表一起加入。

像这样:

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

答案 1 :(得分:1)

您无法更改TMSelection枚举中的项目。

实施例

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
}

要解决此问题,请使用临时列表。

实施例

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

因此,在您的例子中,将新项目添加到临时列表中,然后在foreach循环之后将每个项目添加到主列表中。