我正在尝试检查数据库表“用户”以查看“用户名”是否存在,以便无法再次创建相同的用户名。我希望这是一个验证器,所以如果用户名存在,消息框将显示它存在。
请指导我完成此操作,到目前为止,我在按钮后面有以下代码来添加并检查用户名是否存在:
private void btnSignupNew_Click(object sender, EventArgs e)
{
if (txtUsername.Text == "")
{
errorUsername.SetError(txtUsername, "Enter A Username");
}
else if (txtPassword.Text == "")
{
errorPassword.SetError(txtPassword, "Enter A Valid Password");
}
//so if there isnt no error in the fields itll go on and add the data in to the database.
else{
//instance of sqlConnection
SqlConnection con = new SqlConnection("Data Source=etc");
//instance of sqlCommand
SqlCommand cmd = new SqlCommand("INSERT INTO [User] values ('" + txtForename.Text + "', '" + txtSurname.Text + "', '" + txtUsername.Text + "', '" + txtPassword.Text + "' )", con);
con.Open();
cmd.ExecuteNonQuery();
//query executed correcty or not
con.Close();