【问题标题】:"Collection was modified; enumeration operation may not execute" while Dropdown removing item [duplicate]“集合已修改;枚举操作可能无法执行”同时下拉删除项目[重复]
【发布时间】:2016-08-17 11:01:03
【问题描述】:

我有一个与 resx 文件的下拉绑定。当我要删除一些值时,在 foreach 的第一个循环之后我收到错误:

集合已修改;枚举操作可能无法执行

代码

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

现在它工作正常。谢谢!

【问题讨论】:

    标签: c# asp.net dropdown


    【解决方案1】:

    您不能在迭代枚举时修改它。您必须记住要删除的项目,并在 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);
    

    【讨论】:

    • 我这样解决了: 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())); } }
    猜你喜欢
    • 2012-08-24
    • 2015-06-17
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-17
    • 2011-10-05
    • 1970-01-01
    相关资源
    最近更新 更多