【发布时间】:2012-01-30 04:45:43
【问题描述】:
我正在创建一个方法来处理 DataList 中的删除按钮事件,并且它的功能正常,但是我得到了这个异常:
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.
这是我的代码:
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();
}
}
【问题讨论】:
-
也许将数据绑定移出循环。
-
您在 foreach 循环中绑定到 DataList - 这导致集合被修改。
标签: c# asp.net visual-studio-2010 exception-handling datalist