2016-08-17 4 views
-2

resxファイルとのドロップダウンバインディングがあります。私はいくつかの値を削除しようと思った場合、foreachの最初のループの後、私はエラーを取得しています:「コレクションが変更されたため、列挙操作が実行されない」ドロップダウンアイテムを削除する

Collection was modified; enumeration operation may not execute

コードこれをしてください修正する方法

foreach (ListItem item in VoucherTypeDropDownList.Items) 
{ 
    if (!availableVoucherTypesArray.Contains(int.Parse(item.Value))) 
    {     
     VoucherTypeDropDownList.Items.Remove(
      VoucherTypeDropDownList.Items.FindByValue(item.Value.ToString())); 
    } 
} 

==>私は今、その作業罰金をこのよう

for (Int32 i = VoucherTypeDropDownList.Items.Count-1; i >= 0; i--) 
     { 
     ListItem item = VoucherTypeDropDownList.Items[i]; 

     if (!availableVoucherTypesArray.Contains(int.Parse(item.Value))) 
     { 
      VoucherTypeDropDownList.Items.Remove(VoucherTypeDropDownList.Items.FindByValue(item.Value.ToString()));    
     } 
     } 

を解決しました。ありがとう!

答えて

2

列挙を反復処理中に変更することはできません。 foreachループの後に、削除したい項目を覚えておく必要があります。

List<object> items = new List<object> { 1, 2 }; 
object objectToRemove = null; 

foreach (var item in items) 
{ 
    // insert your condition 
    if (false) 
    { 
     objectToRemove = item; 
     break; 
    } 
} 

if (objectToRemove != null) 
    items.Remove(objectToRemove); 
+0

私はこのように解決: ため(のInt32 I = VoucherTypeDropDownList.Items.Count-1; I> = 0; i--){ リストアイテムのアイテム= VoucherTypeDropDownList.Items [I]。 なら{ VoucherTypeDropDownList.Items.Remove(VoucherTypeDropDownList.Items.FindByValue(item.Value.ToString()))(availableVoucherTypesArray.Contains(int.Parse(item.Value))!)。 } } – Liton

関連する問題