这是C#中的按钮代码,用于检查用户输入的用户名和密码是否正确,如果信息正确,则登录表单(LoginForm)应该消失,而另一表单应该打开(Smart_Pharmacy),为什么不输入? LoginForm打开时Smart_Pharmacy消失了吗?

private void LoginBTN_Click(object sender, EventArgs e)
{
     SqlConnection con = new SqlConnection("Data Source=Abdullah-PC;Initial Catalog=SmartPharmacyDB;Integrated Security=True");
     SqlCommand com = new SqlCommand();
     com.Connection = con;
     com.CommandText = "select userpass from usertab where username = @username";
     com.Parameters.Add("@username", usernametxt.Text);
     con.Open();
     string returneduserpass = com.ExecuteScalar().ToString();
     con.Close();
     if (returneduserpass == userpasstxt.Text)
     {
         Smart_Pharmacy f = new Smart_Pharmacy();
         f.Show();
         LoginForm l = new LoginForm();
         l.Close();
     }
     else
     {
         MessageBox.Show("Incorrect username or password !");
     }
}

最佳答案

为什么Smart_Pharmacy打开时LoginForm不会消失?


您正在创建LoginForm的新实例,并试图关闭该实例。您应该尝试关闭当前打开的LoginForm。

将您的代码更改为:

private void LoginBTN_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("Data Source=Abdullah-PC;Initial Catalog=SmartPharmacyDB;Integrated Security=True");
    SqlCommand com = new SqlCommand();
    com.Connection = con;
    com.CommandText = "select userpass from usertab where username = @username";
    com.Parameters.Add("@username", usernametxt.Text);
    con.Open();
    string returneduserpass = com.ExecuteScalar().ToString();
    con.Close();
    if (returneduserpass == userpasstxt.Text)
    {
        Smart_Pharmacy f = new Smart_Pharmacy();
        f.Show();
        this.Close(); //'this' is the current form(LoginForm)
     }
     else
     {
        MessageBox.Show("Incorrect username or password !");
     }
}

关于c# - 表格不会关闭,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20495591/

10-13 08:12