Click here to Skip to main content
15,923,164 members
Please Sign up or sign in to vote.
3.00/5 (2 votes)
See more:
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:

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


VB
[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:

C#
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
Posted

Items are populated based on Datasource, when you do this:
C#
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[^]

I guess it should help if you move DataSource assignment and DataBind() outside the loop.
 
Share this answer
 
v2
Comments
BillWoodruff 9-Oct-14 5:46am    
+5 Good direct answer.
tina_overgaard 9-Oct-14 16:54pm    
This help me, thanks a lot for the quick repley :-)
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:
C#
Dictionary<string,> dctStrStr = new Dictionary<string,>
{
   {"1", "1"},
   {"2", "2"},
   {"3", "3"},
   {"4", "4"},
   {"5", "5"},
};
This will fail: collection modified error:
C#
foreach (var theKey in dctStrStr.Keys)
{
    dctStrStr[theKey] += " modified";
}
This is okay:
C#
foreach (var theKey in dctStrStr.Keys.ToList())
{
    dctStrStr[theKey] += " modified";
}
And this is okay:
C#
foreach (string sKey in dctStrStr.Select(kvp => kvp.Key).ToList()) 
{
    dctStrStr[sKey] += " modified";
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900