I am trying to insert some data to the sql server but I am getting the error message like “Violation of PRIMARY KEY constraint ‘PK_login1’. Cannot insert duplicate key in object ‘dbo.login1’. The statement has been terminated.”. I have tried to remove the primary key constraint from the table, after that I see that it is inserting more then two similar kind of data into the table. My code is
protected void btn_Submit_Click(object sender, EventArgs e)
{
try
{
SqlCommand cmd;
str = "Insert into login1 values ('" + txtbx_Uname.Text + "', '" + txtbx_Pwd.Text + "', '" + txtbx_Email.Text + "', '" + txtbx_Dob.Text + "', " + txtbx_Phone.Text + ")";
con.Open();
cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
lbl_Error.Visible = true;
lbl_Error.Text = "Registration Success";
int n = Convert.ToInt32(cmd.ExecuteScalar());
if(n==1)
Response.Redirect("Login.aspx");
con.Close();
}
catch
{
lbl_Error.Visible = true;
lbl_Error.Text = "SQL Server Error. Pleaase try after sometime";
}
}
You are using
cmd.ExecuteNonQuery();andint n = Convert.ToInt32(cmd.ExecuteScalar());which will do the same job here.If you want the status of new record that has been inserted to the table, then change the query to stored procedure or use another query for find out the count of record with the field mentioned.
try the following code.
Hope this will fix the issue.