【发布时间】:2015-02-03 16:12:25
【问题描述】:
我有循环每一行的网格视图,但我收到了这个错误:
The variable name '@UserId' has already been declared. Variable names must be unique within a query batch or stored procedure
我已经修复了连接问题,但现在我看到了新问题。请帮忙。
protected void btn_App_Click(object sender, EventArgs e)
{
using (SqlConnection myCon = new SqlConnection(strConnString))
{
using (SqlCommand myCmd = new SqlCommand())
{
myCmd.Connection = myCon;
myCon.Open();
foreach (GridViewRow row in myGV.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Label UserId = row.FindControl("lblUsrID") as Label;
TextBox Start_Date = row.FindControl("txtStartDate") as TextBox;
TextBox End_Date = row.FindControl("txtEndDate") as TextBox;
CheckBox Reg_Appr = ((CheckBox)row.FindControl("txtchkUsrApp")) as CheckBox;
string myUserID = UserId.Text;
myCmd.CommandType = CommandType.Text;
myCmd.CommandText = "update myTable set Start_Date = @Start_Date, End_Date = @End_Date, Reg_Appr = @Reg_Appr where UserId = @UserId ";
myCmd.Parameters.Add("@UserId", SqlDbType.VarChar).Value = UserId.Text;
myCmd.Parameters.Add("@Start_Date", SqlDbType.VarChar).Value = Start_Date.Text;
myCmd.Parameters.Add("@End_Date", SqlDbType.VarChar).Value = End_Date.Text;
myCmd.Parameters.Add("@Reg_Appr", SqlDbType.Bit).Value = Reg_Appr.Checked;
myCmd.ExecuteNonQuery();
SendActivationEmail(myUserID);
}
}
myCon.Close();
}
}
}
//send email
private void SendActivationEmail(string myUserID)
{
// send email
}
【问题讨论】:
-
你有两次
myCon.Close()。没有必要,甚至一次都没有,因为您将它包装在using块中。此外,您的foreach循环也应该封装您的 using 语句。 -
循环内部有
myCon.Open(),外部有Close()。将Open()移到循环之外。 -
另外,你真的希望
ExecuteNonQuery()在循环之外吗?只会更新 GridView 中最后一行的表格