Collection was modified; enumeration operation may not execute.的异常处理

在运行程序时遇到这样一段异常,仔细检查后发现是使用Foreach...In语法体内运用了对Collection的Remove或Add导致的,只需要将foreach方法改为for方法即可。

    for (int i = 0; i < this.prtdeallist.Items.Count; i++)
            {
                RepeaterItem repeaterItem = this.prtdeallist.Items[i];
                
         
                if (repeaterItem.ItemType == ListItemType.Item || repeaterItem.ItemType == ListItemType.AlternatingItem)
                {
                    HtmlInputCheckBox cbDealIsSelected = repeaterItem.FindControl("ckPpGuid") as HtmlInputCheckBox;
                    HiddenField hfDealGuid = repeaterItem.FindControl("HiddenField2") as HiddenField;
                    if (cbDealIsSelected.Checked )
                    {                        
                        DTDealItemWrapper DealItem = DTDealItemWrapper.FindById(hfDealGuid.Value);
                        DTDealWrapper DTdeal = null;
                        if (DealItem == null)
                        {
                            DTdeal = DTDealWrapper.FindById(hfDealGuid.Value);
                        }
                        if (DealItem != null)
                        {
                            DealItem.DDICRMReportStatus = false;
                            DTDealItemWrapper.Update(DealItem);
                            string LineCode = "LineCode:" + DealItem.DDILineCode;
                            RecordDeleteLog(hfDealGuid.Value, LineCode);
                        }
                        else if (DTdeal != null)
                        {
                            DTdeal.DDCRMReportStatus = false;
                            DTDealWrapper.Update(DTdeal);
                            string LineCode = "DD_NO:" + DTdeal.DDNo;
                            RecordDeleteLog(hfDealGuid.Value, LineCode);
                        }


                      
                    }

                }
            }

  

原文地址:https://www.cnblogs.com/wangguowen27/p/Collection.html