[英]Log In from Toolstrip Menu Item and UserControl Button in C# WinForm
我不知道解決方案。
這是簡要說明。
我有一個名為“ frmMain”的主窗體,該窗體有一個MenuStrip,其中包含一個名為“ mnuFile”的ToolStripMenuItem,它又包含一個名為“ mnuLogIn”的ToolStripMenuItem。
同時,主窗體還包含一個名為“ panel2”的面板,該面板將在窗體加載時保存名為“ uc_MainMenu”的用戶控件的實例。 該用戶控件有幾個按鈕,其中之一是名為“ btnLogIn”的按鈕。
結構是,如果用戶從“ mnuLogIn”或“ btnLogIn”輸入正確的用戶名和密碼,我希望用戶能夠登錄。 單擊這些按鈕之一時,將顯示“ frmLogIn”。
成功登錄后,“ mnuLogIn”或“ btnLogIn”都將其文本從“ LogIn”更改為“ LogOut”。
我以以下主要形式編寫了用於登錄的方法。
internal void mnuLogIn_Click(object sender, EventArgs e)
{
ShowLogIn();
}
internal void ShowLogIn()
{
if (this.mnuLogIn.Text == "LogOut" )
{
if (MessageBox.Show("Are you sure you want to LogOut?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
mnuLogIn.Text = "LogIn";
ShowMenu("");
obj_uc_MainMenu.Log_Out_Button = new Button();
}
return;
}
frmLogin obj_frmLogin = new frmLogin();
//followed by checking the username and password
//the procedure repeated until the log-in is successful
mnuLogIn.Text = "LogOut";
obj_uc_MainMenu.Log_In_Button = new Button();
}
在用戶控件“ uc_MainMenu”中
public Button Log_In_Button
{
get { return btnLogIn; }
set { btnLogIn.Text = "LOGOUT"; }
}
private void btnLogIn_Click(object sender, EventArgs e)
{
frmMain obj_frmMain = new frmMain();
obj_frmMain.mnuLogIn_Click(sender,e);
}
運行這段代碼
1)“ mnuLogIn”登錄
當我嘗試通過“ mnuLogIn”按鈕登錄時,一切都很好。 obj_uc_MainMenu中的“ mnuLogIn”和“ btnLogIn”都將其文本從“ LogIn”更改為“ LogOut”。
2)“ btnLogIn”登錄
當我嘗試通過“ btnLogIn”按鈕登錄時,出現了“ frmLogin”。 它非常適合檢查用戶名和密碼步驟。 但是,在“ frmLogin”對話框中單擊“登錄”按鈕后,什么也沒發生。 “ mnuLogIn”和“ btnLogIn”均未更改其文本。
到底是怎么回事?
哦,我忘了提及,“ frmLogin”中的“登錄”按鈕的DialogResult已設置為“確定”。 因此,“ frmLogin”內部沒有任何代碼。
我建議您將代碼更改為這種方法。
// This should be public to be callable from the usercontrol
public void ShowLogIn()
{
if (this.mnuLogIn.Text == "LogOut" )
{
if (MessageBox.Show("Are you sure you want to LogOut?", "Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
mnuLogIn.Text = "LogIn";
ShowMenu("");
// Call the user control to adjust its internal status
obj_uc_MainMenu.SetLoginStatus();
}
}
else
{
using(frmLogin obj_frmLogin = new frmLogin())
{
if(obj_frmLogin.ShowDialog() == DialogResult.OK)
{
// Check the username and password and if everythin ok then
mnuLogIn.Text = "LogOut";
// Again call the usercontrol to adjust its status
obj_uc_MainMenu.SetLogoutStatus()
}
}
}
}
public void SetLoginStatus()
{
btnLogIn.Text = "LOGIN";
}
public void SetLogoutStatusStatus()
{
btnLogIn.Text = "LOGOUT";
}
private void btnLogIn_Click(object sender, EventArgs e)
{
// Get the current instance of frmMain from the OpenForms collection
frmMain obj_frmMain = Application.OpenForms.OfType<frmMain>();
// Should not be required, but better to be safe....
if(obj_frmMain != null)
// Call the public method to run the login process
obj_frmMain.ShowLogin();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.