Click here to Skip to main content
15,917,862 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Collection was modified; enumeration operation may not execute.

C#
void counts()
    {
        foreach(RepeaterItem items in repeat.Items)
        {
            HiddenField comment_like = (HiddenField)items.FindControl("comment_like");
            Label user_counts = (Label)items.FindControl("user_counts");
         
            if (Request.QueryString["id"] != null)
            {
                int id;
                id = Convert.ToInt32(Request.QueryString["id"].ToString());
                con = new SqlConnection(str);
                con.Open();
                cmd = new SqlCommand("sp_command_count", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@eid", id);
                cmd.Parameters.AddWithValue("@comment_id", comment_like.Value);
                da = new SqlDataAdapter(cmd);
                dt = new DataTable();
                da.Fill(dt);
                con.Close();

                if (dt.Rows.Count > 0)
                {
                    DataRow dr = dt.Rows[0];
                    user_counts.Text = dr["total_count"].ToString() + "of" + dr["like_count"].ToString();

                    repeat.DataSource = dt;
                    repeat.DataBind();
                    review_panel.Visible = true;
                }
                else
                {
                    review_panel.Visible = false;
                }
            }
        }
    }
Posted
Updated 1-Mar-15 19:35pm
v2

1 solution

The problem is that inside your foreach loop you re-create the items of the repeater (it happens when you are re-bind it to new data)...
When enumerating the elements of the collection, at the very beginning, the framework creates an enumerator - a kind of pointer that enables traversing the elements by registering them with a unique id...When you change the collection (in your case by re-creating the elements, but also adding or deleting can do) the enumerator becomes invalid and can not be used...
 
Share this answer
 
Comments
Member 10918596 2-Mar-15 1:46am    
how to slove this error example
Kornfeld Eliyahu Peter 2-Mar-15 1:50am    
I can not say, as I can not understand your purpose...
Maciej Los 2-Mar-15 1:58am    
+5!
Kornfeld Eliyahu Peter 2-Mar-15 1:58am    
Thank you...
Thanks7872 2-Mar-15 2:09am    
I like such answers..+5!

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


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