我想创建一个简单的表单,我想要验证以显示相同用户存在的消息。窗体如何在数据库中检查用户是否已经存在?
函数usernamecheck()检查验证并显示错误,如果同一个用户存在,但当我点击提交按钮它仍然提交相同的用户。
private void submit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=LFC;Initial Catalog=contactmgmt;Integrated Security=True";
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO cntc_employee (emp_f_name,emp_l_name,emp_alias,emp_contact_no,emp_address,emp_company,emp_bdate) VALUES(@fname,@lname,@alias,@contact,@address,@company,@bdate)";
cmd.Connection = con;
cmd.Parameters.AddWithValue("@fname", textBox1.Text);
cmd.Parameters.AddWithValue("@lname", textBox2.Text);
cmd.Parameters.AddWithValue("@alias", textBox3.Text);
cmd.Parameters.AddWithValue("@contact", textBox4.Text);
cmd.Parameters.AddWithValue("@address", textBox5.Text);
cmd.Parameters.AddWithValue("@company", textBox6.Text);
cmd.Parameters.AddWithValue("@bdate", textBox7.Text.ToString());
UserNameCheck();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Data Inserted Succesfully");
}
public void UserNameCheck()
{
string constring = "Data Source=LFC;Initial Catalog=contactmgmt;Integrated Security=True";
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand("Select * from cntc_employee where emp_alias= @alias", con);
cmd.Parameters.AddWithValue("@alias", this.textBox3.Text);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("Alias "+ dr[1].ToString() +" Already exist");
break;
}
}
}
你确定你的'UserNameCheck '完全按照你想要的方式工作?你调试了你的代码吗?并使用'使用语句'来处置你的'SqlConnection'和'SqlCommand' –
你能告诉我们'usernamecheck()'函数代码吗? –
是的,它的作品,我认为我做错了最后3行 – skates008