0

I have a registration form where on button click a stored procedure in a SQL Server is called and a new row is inserted. The problem is when I click (no accidental double clicks) two rows of the same entry is inserted. I have gone through my codes thoroughly but I could not find the issue.

C# button click code:

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()
        }
    }
}

My SQL Server stored procedure:

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

1 Answer 1

2

The problem is in these two lines :

   insertUser.ExecuteNonQuery();

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

You're executing the insertUser Command twice; in ExecuteNonQuery and in ExecuteScalar .

Sign up to request clarification or add additional context in comments.

1 Comment

Oh yes.. thank u. i have overlooked that.. Let me edit and verify

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.