2012-02-14 10 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ループ内にアイテムを追加している可能性があります。 –

答えて

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

だからあなたexmapleで、その後、foreachループの後にメインリストに各項目を追加し、一時リストに新しいアイテムを追加します。