gpt4 book ai didi

c# - InvalidOperationException 错误

转载 作者:太空狗 更新时间:2023-10-30 01:08:42 25 4
gpt4 key购买 nike

我正在创建一个方法来处理 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();
}
}

最佳答案

DataList2.DataBind();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();

关于c# - InvalidOperationException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8673399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com