2016-08-17 78 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 = VoucherTypeDropDownList.Items.Count-1; I> = 0;我 - ) { 列表项项= VoucherTypeDropDownList.Items [I]; 如果 { VoucherTypeDropDownList.Items.Remove(VoucherTypeDropDownList.Items.FindByValue(item.Value.ToString()))(availableVoucherTypesArray.Contains(int.Parse(item.Value))!); } } – Liton

相关问题