[英]Form won't close
这是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 !");
}
}
您正在创建表单的新实例并关闭该实例,因此它不会影响您实际要关闭的表单。
假设LoginBTN_Click
是您的表单类的成员,则只需编写以下内容:
if (returneduserpass == userpasstxt.Text)
{
Smart_Pharmacy f = new Smart_Pharmacy();
f.Show();
this.Close(); // or simply 'Close()'.
}
看起来您正在实例化一个新的LoginForm,然后立即关闭该窗体。
请尝试关闭当前处于活动状态的表单:
if (returneduserpass == userpasstxt.Text)
{
Smart_Pharmacy f = new Smart_Pharmacy();
f.Show();
this.Close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.