C#ASP.NET,SQL Server:Button Click插入重复的行

时间:2017-08-27 07:50:00

标签: c# sql-server

我有一个注册表单,其中按钮单击调用SQL Server中的存储过程并插入新行。问题是当我点击(没有意外双击)插入相同条目的两行时。我彻底完成了我的代码,但我找不到问题。

C#按钮点击代码:

protected void Button1_Click(object sender, EventArgs e)
{
    int userId = 0;
    string constr = ConfigurationManager.ConnectionStrings["islamguiderConnectionString"].ConnectionString;

    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand insertUser = new SqlCommand("Register_Student"))
        {  
            insertUser.CommandType = CommandType.StoredProcedure;

            insertUser.Parameters.AddWithValue("@StudentName", TextBox1.Text.ToUpper());
            insertUser.Parameters.AddWithValue("@Email", TextBox4.Text.ToLower());
            insertUser.Parameters.AddWithValue("@CourseCode", DropDownList2.SelectedValue);
            insertUser.Parameters.AddWithValue("@CourseTitle", DropDownList2.SelectedItem.ToString());

            insertUser.Connection = con;

            con.Open();
            insertUser.ExecuteNonQuery();

            userId = Convert.ToInt32(insertUser.ExecuteScalar());
            Con.Close()
        }
    }
}

我的SQL Server存储过程:

CREATE PROCEDURE [dbo].[Register_Student]
    @StudentName NVARCHAR(200),
    @Email NVARCHAR(200),
    @CourseCode NVARCHAR(200),
    @CourseTitle NVARCHAR(200)
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @ID INT 

    INSERT INTO dbo.Registration_Table (StudentName,Email, CourseCode, CourseTitle) 
    VALUES (@StudentName, @Email, @CourseCode, @CourseTitle)  

    SELECT 2
END

1 个答案:

答案 0 :(得分:2)

问题在于以下两行:

   insertUser.ExecuteNonQuery();

   userId = Convert.ToInt32(insertUser.ExecuteScalar());

您执行insertUser命令两次;在ExecuteNonQueryExecuteScalar