我举个例子:
简单的登录和验证。
重要代码:
Login_in f2 = new Login_in(); //Create login window
this.Hide(); //Hide the main window
f2.ShowDialog(); //Show login window
this.Show(); //Show main window
主窗口:
private void Button1_Click(object sender, EventArgs e)
{
Login_in f2 = new Login_in();
while (true)
{
this.Hide();
f2.ShowDialog();
if (f2.DialogResult == DialogResult.OK)
{
this.Show();
MessageBox.Show("Verification Success!");
break;
}
else if (f2.DialogResult == DialogResult.Cancel)
{
this.Show();
MessageBox.Show("Verification Failed");
break;
}
f2.Close();
}
}
登录窗口:
private void Button1_Click(object sender, EventArgs e)
{
//Personal test database
string myconn = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = Test; Integrated Security = True";
SqlConnection conn = new SqlConnection(myconn);
string sql= $"select * from Test.dbo.demoAccount where userid=@UserId and password=@PassWord";
try
{
conn.Open();
SqlCommand sqlCommand = new SqlCommand(sql, conn);
//sqlCommand.Parameters.AddWithValue("@UserId", AccountTb.Text.Trim())
//sqlCommand.Parameters.AddWithValue("@PassWord", PassTb.Text.Trim());
sqlCommand.Parameters.Add("@UserId", SqlDbType.VarChar, 8).Value = AccountTb.Text.Trim();
sqlCommand.Parameters.Add("@PassWord", SqlDbType.Char, 8).Value = PassTb.Text.Trim();
SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
if (sqlDataReader.HasRows) //Satisfy the user name and password are consistent, enter the next interface
{
this.DialogResult = DialogResult.OK;
}
else
{
this.DialogResult = DialogResult.Cancel;
}
conn.Close();
}
catch (Exception o)
{
MessageBox.Show(o.ToString());
}
}
输出:
如果您对我的代码有任何疑问,请在下方发表评论。更新问题,我会继续改进的。
更新:
- 在子窗口中添加委托和事件。类似代码如下。由于需要传递字符串,所以委托需要带字符串参数。
public delegate void MyAccountDelegate(string account);
public event MyAccountDelegate MyAccountEvent;
- 设置子窗口中Login按钮的事件,在点击时调用上述事件,并将需要传递的字符串传递给事件。
if (sqlDataReader.HasRows)//Satisfy the user name and password are consistent, enter the next interface
{
this.DialogResult = DialogResult.OK;
MyAccountEvent(AccountTb.Text);//Add account information
} else
{
this.DialogResult = DialogResult.Cancel;
}
- 增加在主窗口显示返回信息的方法,与参与MyAccountDelegate委托相同。
private void DisplayMyAccount(string account) {
listBox1.Items.Add(account);
}
- 添加如下代码,在父窗口的登录按钮中打开子窗口:
f2.MyAccountEvent += new Login_in.MyAccountDelegate(DisplayMyAccount);
//f2.MyAccountEvent += DisplayMyAccount;
提示:这里使用的(关闭)主窗口是一种隐藏方式,并不是真正关闭,所以不会影响主窗口信息:
this.Hide();
this.show();
输出:
根据需要自行更改,请检查我是否理解您的意思。