Error InvalidOperationException

I create a method to handle the delete button event inside a DataList, and it performs the function correctly, however I get this exception:

Collection was modified; enumeration operation may not execute. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: Collection was modified; enumeration operation may not execute. 

and this is my code:

 protected void delete(object sender, CommandEventArgs e) { if ((e.CommandName == "delete") && (e.CommandArgument != null)) { foreach (DataListItem item in DataList2.Items) { Label post_IDLabel = (Label)item.FindControl("post_IDLabel"); string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString(); SqlConnection conn = new SqlConnection(connStr); SqlCommand cmd = new SqlCommand("delete_post", conn); cmd.CommandType = CommandType.StoredProcedure; int post_ID = Convert.ToInt32(post_IDLabel.Text); string email = Session["email"].ToString(); int course_ID = Convert.ToInt32(Request.QueryString["courseID"]); cmd.Parameters.Add(new SqlParameter("@course_ID", course_ID)); cmd.Parameters.Add(new SqlParameter("@myemail", email)); cmd.Parameters.Add(new SqlParameter("@post_ID", post_ID)); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); DataList2.DataBind(); } } 
+4
source share
3 answers

Take DataList2.DataBind(); from foreach

  foreach (DataListItem item in DataList2.Items) { Label post_IDLabel = (Label)item.FindControl("post_IDLabel"); string connStr = ConfigurationManager.ConnectionStrings["MyDbConn"].ToString(); SqlConnection conn = new SqlConnection(connStr); SqlCommand cmd = new SqlCommand("delete_post", conn); cmd.CommandType = CommandType.StoredProcedure; int post_ID = Convert.ToInt32(post_IDLabel.Text); string email = Session["email"].ToString(); int course_ID = Convert.ToInt32(Request.QueryString["courseID"]); cmd.Parameters.Add(new SqlParameter("@course_ID", course_ID)); cmd.Parameters.Add(new SqlParameter("@myemail", email)); cmd.Parameters.Add(new SqlParameter("@post_ID", post_ID)); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } DataList2.DataBind(); 
+2
source

You cannot modify a collection while it is being listed. DataList2.DataBind modifies DataList2.Items , which is not valid.

If you move the DataBind out of the loop, it should work.

+2
source

I think your problem is resolved when you move DataList2.DataBind from foreach.

But I think there are more errors with your code, you should try to avoid calling the database from the loop. You should try to reorganize this code so that you only make one call to the database. For example, pass the entire message identifier in one parameter. Or maybe only course_id and email address, if that’s enough.

+1
source

Source: https://habr.com/ru/post/1388516/


All Articles