我使用 if else 语句在我的程序中检查了这个错误。我有两件事要检查。他们是
警察ID(PK)
身份证
下面的语句检查文本框是否具有与数据库中相同的 PoliceID 和 NRIC 值。
if (tbpid.Text.Equals(dr["policeid"].ToString().Trim()) && (tbnric.Text.Equals(dr["nric"].ToString().Trim())))
{
lbmsg.Text = "This police account has already exist. Please verify the details again.";
}
如果文本框(警察 id)与数据库中的值相同,它们将给出另一个不同的错误。
if (tbpid.Text.Equals(dr["policeid"].ToString()))
{
lbmsg.Text = "This police ID has already exists. Please generate another Police ID";
}
如果文本框 (NRIC) 与数据库中的值相同,则会出现另一个错误
if (tbnric.Text.Equals(dr["nric"].ToString()))
{
lbmsg.Text ="This NRIC has already exist. Please ensure that the NRIC is correct";
}
如果我将所有错误检查消息组合在一起,它将是这样的。
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().Trim()) && (tbnric.Text.Equals(dr["nric"].ToString().Trim())))
{
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 Police ID";
}
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";
}
//ConfirmButtonExtender2.ConfirmText = "Are you sure you want to add this Police Account " + tbpid.Text + " ?";
}
}
但是这里的问题是,错误检查消息的前两个语句设法工作。不幸的是,身份证没有工作。例如,如果我输入不同的policeID 但相同的身份证,数据仍被插入到数据库中,这意味着它完全忽略了上面的身份证错误检查。我已经看了好几个小时了,我还没有找到问题所在。如果有人可以指导我,将不胜感激。
另外,在我的数据库中,我已将主键设置为policeID,而NRIC只是我数据库中的常规数据列
问候。