我收到此错误:收集已修改;枚举操作可能无法执行。

问题描述:

您好b $ b

我有这个问题。我有这个带有数量的文本框,可以根据需要进行更改。我第一次做出改变是有效的,但第二次我得到这个错误收集被修改了;枚举操作可能无法执行。



我不知道错误是什么。这是我的清单吗?



这是完整的错误代码:



Hi
I have this issue. I have this textbox with quantity, and it could be possible to make an change as much as you like. The first time I make a change it works, but the second time I got this error Collection was modified; enumeration operation may not execute.

And I don´t have any clue what the error is. It is something about my list?

Here is the fulll error code:

Line 83:                             List<OrdreNew> produktOrdreNew = new List<OrdreNew>();
Line 84:
Line 85:                                     foreach (RepeaterItem items in Repeater1.Items)
Line 86:                                     {
Line 87:







[InvalidOperationException: Collection was modified; enumeration operation may not execute.]
   System.Collections.ArrayListEnumeratorSimple.MoveNext() +11165697
   kassen.Button1_Click(Object sender, EventArgs e) in c:\Users\Tina\Desktop\tojbutik\kassen.aspx.cs:85
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9628026
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724











这是我的代码:








And here is my code:

public partial class kassen : System.Web.UI.Page
{
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            
            Repeater1.Visible = false;
            List<Produkt> produkter = Session["OrdreComplete"] as List<Produkt>;

            List<ordre> produktOrdre = new List<ordre>();

            foreach (var produkt in produkter)
            {
                produktOrdre.Add(new ordre { produktID = produkt.ID, Produktoverskrift = produkt.overSkrift, produktStr = produkt.STR, produktAntal = produkt.Antal, produktPris = produkt.PRICE });

            }

            this.RepeaterVisOrdre.DataSource = produktOrdre;
            this.RepeaterVisOrdre.DataBind();

           
        }     

    }

    protected void RepeaterVisOrdre_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            DataRowView row = e.Item.DataItem as DataRowView;
            Label LabelID = e.Item.FindControl("LabelID") as Label;
            Label LabelVare = e.Item.FindControl("LabelVare") as Label;
            Label LabelStr = e.Item.FindControl("LabelStr") as Label;
            Label LabelPris = e.Item.FindControl("LabelPris") as Label;
            TextBox TextBox1 = e.Item.FindControl("TextBox1") as TextBox;

            TextBox tb = (TextBox)e.Item.FindControl("TextBox1");

            //LabelVare.Attributes.Add("IDprodukt", string.Format("{0}", row["LabelVare"]));
            //LabelVare.Attributes.Add("vareBeskriv", string.Format("{0}", row["overskriftt"]));
            //LabelStr.Attributes.Add("STR", string.Format("{0}", row["produktStr"]));
            //LabelPris.Attributes.Add("PRICE", string.Format("{0}", row["str"]));
            //LabelAntal.Attributes.Add("Antal", string.Format("{0}", row["produktAntal"]));
            //TextBox1.Attributes.Add("Antal", string.Format("{0}", row["produktAntal"]));


        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {

                        if (Session["Ordre"] !=  null)
                        {
                            
                            List<OrdreNew> produktOrdreNew = new List<OrdreNew>();
                          
                                    foreach (RepeaterItem items in Repeater1.Items)
                                    {
                                
                                        if (items.ItemType == ListItemType.Item || items.ItemType == ListItemType.AlternatingItem)
                                        {
                                            
                                            Label LabelID = (Label)items.FindControl("LabelID");
                                            Label LabelVare = (Label)items.FindControl("LabelVare");
                                            Label LabelStr = (Label)items.FindControl("LabelStr");
                                            Label LabelPris = (Label)items.FindControl("LabelPris");

                                            TextBox tb = (TextBox)items.FindControl("TextBox1");

                                            int id = Convert.ToInt32(LabelID.Text);
                                            int newAntal = Convert.ToInt32(tb.Text);
                                            string vare = LabelVare.Text;
                                            string str = LabelStr.Text;
                                            int prise = Convert.ToInt32(LabelPris.Text);


                                            produktOrdreNew.Add(new OrdreNew() { produktID = id, Produktoverskrift = vare, produktStr = str, produktAntal = newAntal, produktPris = prise });
                                    

                                            Repeater1.Visible = true;
                                            Repeater1.DataSource = produktOrdreNew;
                                            Repeater1.DataBind();

                                            RepeaterVisOrdre.Visible = false;


                                        }
                                        
                                    }
                                    Session["OrdreNew"] = produktOrdreNew;
                                    List<OrdreNew> produktOrdreNew1 = (List<OrdreNew>)Session["OrdreNew"];
                                    foreach (OrdreNew produkt in produktOrdreNew1)
                                    {
                                        Label1.Text += "Label fra repeater 1 ID " + produkt.produktID + " " + "Vare nr :" + produkt.Produktoverskrift + " " + "Størrelse :" + produkt.produktStr + " " + " Antal : " + produkt.produktAntal + " " + " Pris : " + produkt.produktPris;
                                    }
                                   
                    

                        }
                        else
                        {
                            List<ordreEnd> produkt1 = new List<ordreEnd>();
                            foreach (RepeaterItem item in RepeaterVisOrdre.Items)
                            {
                                if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)
                                {
                            
                                        Label LabelID = (Label)item.FindControl("LabelID");
                                        Label LabelVare = (Label)item.FindControl("LabelVare");
                                        Label LabelStr = (Label)item.FindControl("LabelStr");
                                        Label LabelPris = (Label)item.FindControl("LabelPris");

                                        TextBox tb = (TextBox)item.FindControl("TextBox1");

                                        int id = Convert.ToInt32(LabelID.Text);
                                        int newAntal = Convert.ToInt32(tb.Text);
                                        string vare = LabelVare.Text;
                                        string str = LabelStr.Text;
                                        int prise = Convert.ToInt32(LabelPris.Text);


                                        produkt1.Add(new ordreEnd() { produktID = id, Produktoverskrift = vare, produktStr = str, produktAntal = newAntal, produktPris = prise });
                                        



                                        Repeater1.Visible = true;
                                        Repeater1.DataSource = produkt1;
                                        Repeater1.DataBind();

                                        RepeaterVisOrdre.Visible = false;
                                }
                            }
                            Session["Ordre"] = produkt1;

                            List<ordreEnd> valgteFrugter = (List<ordreEnd>)Session["Ordre"];
                            foreach (ordreEnd produkt in valgteFrugter)
                            {
                                Label1.Text += "Label fra repeaterVisOrdre ID " + produkt.produktID + " " + "Vare nr :" + produkt.Produktoverskrift + " " + "Størrelse :" + produkt.produktStr + " " + " Antal : " + produkt.produktAntal + " " + " Pris : " + produkt.produktPris;
                            }
                           
                        }
        
    }

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Session.Abandon();
    }
}





希望有人能帮我解决这个错误



Hope someone could help me with this error

当您执行此操作时,将根据数据源填充项目:

Items are populated based on Datasource, when you do this:
Repeater1.DataSource = produktOrdreNew;
Repeater1.DataBind();



那么你有不同的项目:


then you have different items in:

Repeater1.Items



http ://msdn.microsoft.com/pl-pl/library/system.web.ui.webcontrols.repeater.items(v = vs.110).aspx [ ^ ]



我想如果你在循环外移动DataSource赋值和DataBind()会有所帮助。


http://msdn.microsoft.com/pl-pl/library/system.web.ui.webcontrols.repeater.items(v=vs.110).aspx[^]

I guess it should help if you move DataSource assignment and DataBind() outside the loop.


尝试使用for循环当您修改正在迭代的集合中的对象时,迭代集合而不是foreach。



请参阅Jared Par的代码:[ ^ ];该线程对这个问题的不同方面进行了很好的讨论。



允许你使用foreach迭代器的另一个策略是在对象的foreach迭代器中构建一个List你希望修改,然后,在迭代完成后,通过遍历该列表来修改那些对象。



删除时的常用策略使用for循环的Collection中的项目以端到端的顺序遍历循环,以便索引保持有意义。



另一个策略是投射你的无论你在迭代到另一个List,甚至是一个允许你使用foreach的数组。



给出这样的字典:
Try using for-loops to iterate over the collection instead of foreach when you modify objects in the collection you are iterating over.

See Jared Par's code here: [^]; that thread has a good discussion of different aspects of this problem.

Another strategy that allows you to use a foreach iterator is to build a List in the foreach iterator of objects you wish to modify, and then, after the iteration is complete, modify only those objects by iterating over that List.

A common strategy when removing items from a Collection using a for-loop is traverse the loop in end-to-front order so that indexes remain meaningful.

Another strategy is to Cast your whatever-you-are-iterating to another List, or even an Array, which lets you use foreach.

Given a Dictionary like this:
Dictionary<string,> dctStrStr = new Dictionary<string,>
{
   {"1", "1"},
   {"2", "2"},
   {"3", "3"},
   {"4", "4"},
   {"5", "5"},
};

这将失败:收集修改错误:

This will fail: collection modified error:

foreach (var theKey in dctStrStr.Keys)
{
    dctStrStr[theKey] += " modified";
}

这没关系:

foreach (var theKey in dctStrStr.Keys.ToList())
{
    dctStrStr[theKey] += " modified";
}

这没关系:

foreach (string sKey in dctStrStr.Select(kvp => kvp.Key).ToList()) 
{
    dctStrStr[sKey] += " modified";
}