2012-02-14 28 views
1

我不知道我在做什麼錯,但我不斷收到此錯誤。有誰知道這可能是什麼原因造成的?C#CheckedListBox在foreach循環上的InvalidOperationException

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

什麼是TMSelection?這可能是因爲你在foreach循環中添加了一個項目。 – 2012-02-14 22:06:56

回答

1

的枚舉,如果列表不改變,只能使用。

創建的要添加,然後加入你要修改的列表列表什麼其他列表。

像這樣:

List toAdd = new List() 
for(Object item in list) { 
    if(whatever) { 
     toAdd.add(item); 
    } 
} 
list.addAll(toAdd); 
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循環後的每個項目添加到主列表。