当用户尝试使用已经存在的用户名注册时,如何修复 IF 语句。目前,如果用户名已经存在,我的程序将不接受输入的数据,但它仍会进入下一页(即使数据未保存在数据库中)。我需要知道的是如何消除这个问题,所以当用户输入一个存在的“用户名”时,它只会给出错误的消息框,而不是移动到下一页。
谢谢!
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");
}
else
{
using (SqlConnection con = new SqlConnection("Data Source=etc"))
{
con.Open();
bool exists = false;
// create a command to check if the username exists
using (SqlCommand cmd = new SqlCommand("select count(*) from [User] where UserName = @UserName", con))
{
cmd.Parameters.AddWithValue("UserName", txtUsername.Text);
exists = (int)cmd.ExecuteScalar() > 0;
}
// if exists, show a message error
if (exists)
{
MessageBox.Show("Username: " + txtUsername.Text + " already Exists");
//errorPassword.SetError(txtUsername, "This username has been using by another user.");
}
else
{
// does not exists, so, persist the user
using (SqlCommand cmd = new SqlCommand("INSERT INTO [User] values (@Forename, @Surname, @Username, @Password)", con))
{
cmd.Parameters.AddWithValue("Forename", txtForename.Text);
cmd.Parameters.AddWithValue("Surname", txtSurname.Text);
cmd.Parameters.AddWithValue("UserName", txtUsername.Text);
cmd.Parameters.AddWithValue("Password", txtPassword.Text);
cmd.ExecuteNonQuery();
}
}
con.Close();
MessageBox.Show("Sucessfully Signed Up");
Form1 signin = new Form1();
signin.Show();
this.Close();
}
}
}
}