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
.AddWithValue()- it can lead to unexpected and surprising results...