I'm trying to ensure that the user does not insert data that already exists in the database.
I have used datareader to read the data from the SQL server.
protected void btnAdd_Click(object sender, EventArgs e) { SqlConnection con = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI"); con.Open(); SqlCommand select = new SqlCommand("Select policeid, nric from PoliceAccount where policeid = @policeid", con); SqlDataReader dr; select.Parameters.AddWithValue("@policeid", tbpid.Text); dr = select.ExecuteReader(); if (dr.Read()) { if (tbpid.Text.Equals(dr["policeid"].ToString()) && (tbnric.Text.Equals(dr["nric"].ToString()))) { lbmsg.Text = "This police account has already exist. Please verify the details again."; } else if (tbpid.Text.Equals(dr["policeid"].ToString())) { lbmsg.Text = "This police ID has already exists. Please generate another"; } else if (tbnric.Text.Equals(dr["nric"].ToString())) { lbmsg.Text ="This NRIC has already exist. Please ensure that the NRIC is correct"; } } else { SqlConnection conn = new SqlConnection("Data Source = localhost; Initial Catalog = MajorProject; Integrated Security= SSPI"); conn.Open(); SqlCommand cmd = new SqlCommand("insert into PoliceAccount(policeid, password, nric, fullname, postedto) values('" + tbpid.Text.Trim() + "','" + tbpid.Text.Trim() + "','" + tbnric.Text.Trim() + "','" + tbfullname.Text.Trim() + "', '" + ddllocation.SelectedValue + "')", conn); cmd.ExecuteNonQuery(); conn.Close(); lbmsg.Text = "Congratulations. The police account of ID " + tbpid.Text + " has been successfully added. You may edit the profile via the edit profile tab above"; tbpid.Text = ""; tbnric.Text = ""; tbfullname.Text = ""; ddllocation.SelectedValue = "Select Location"; } }
However, when i added `.Text` into NRIC, something weird happens. When i type the same ID but different NRIC, the primary key error appears on my VS2012 (obviously it happens because i added a primary key constraint on pid) which means it totally ignores my duplicate check. However, when i type the different ID but the same NRIC, the information was submitted into the database. which totally ignores the NRIC check that i have done.
I'm still curious to know why this happens.