我正在嘗試模擬對應用程式的登錄。我想從登錄表單,主表單(登錄成功時)打開。我在主表單上有一個按鈕,點擊時必須凍結主表單打開登錄表單,從登錄表單登錄后解凍相同的主表單
uj5u.com熱心網友回復:
我給你舉個例子:
簡單的登錄和驗證。
重要代碼:
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());
}
}

輸出:

如果您對我的代碼有任何疑問,請在下面發表評論。更新問題,我會繼續改進。
更新:
- 在子視窗中添加一個delegate和event。類似的代碼如下。因為需要傳遞一個字串,所以delegate需要帶一個字串引數。
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();
輸出:

根據您的需要自行更改,請檢查我是否理解您的意思。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/379711.html
