如何正确打开登录表单



我的c#windows应用程序中有一个登录表单和MDI主表单。在MDI表单加载事件中,我像这样打开我的登录表单。当登录成功时,它只会退出并启用MDI主窗体。最近我才发现,如果我关闭登录窗体,它就会关闭,然后它会毫无障碍地启用MDI主。

这就是我在MDI主窗体中加载登录名的方式。

private void MDiMain_Load(object sender, EventArgs e)
{
setDisplaysize();
Form newLogin = new FormControllers.FrmLogin();
newLogin.StartPosition = FormStartPosition.CenterScreen;
//newLogin.Show(this);
newLogin.ShowDialog(this);
newLogin.Focus();
newLogin.TopMost = true;
newLogin.Activate();                        
} 

然后我试着用这个代码段来改变我的应用程序

static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
FormControllers.FrmLogin fLogin = new FormControllers.FrmLogin();
if (fLogin.ShowDialog() == DialogResult.OK)
{
Application.Run(new MDiMain());
}
else
{
Application.Exit();
}
}

现在表单登录打开,但成功登录后MDI主表单不会启动。我在这里做错了什么?

此外,这是我在登录表单中的登录按钮代码

private void btnLogin_Click(object sender, EventArgs e)
{
string txtPass = "";
string txttPassword = "";
string txtHoldStr = "";
String txtStringst1 = "";
char chrFstep ='c';
char chrSstep ='c';
int testInt = 0;
using (DataControllers.RIT_Allocation_Entities EntityModel = new DataControllers.RIT_Allocation_Entities())
{
try
{
userHeadModel = EntityModel.TBLU_USERHED.Where(x => x.USERHED_USERCODE == (txtUserName.Text.Trim())).FirstOrDefault();
txtPass = userHeadModel.USERHED_PASSWORD;
txttPassword = txtPassword.Text.Trim();
if (txtPass == txtHoldStr)
{
MessageBox.Show("Login Successful");
this.Close();
}
else
{
MessageBox.Show("Invalid username or password please try again");
txtPassword.Focus();
}
}
catch (Exception ex) { }
}
}

您需要设置对话框结果:

if (txtPass == txttPassword)
{
MessageBox.Show("Login Successful");
DialogResult = DialogResult.OK;
Close();
}

只有默认按钮会自动为您执行此操作。当涉及到逻辑时,您需要根据身份验证的结果(在本例中为(进行设置。

除此之外,我想原始代码中与txtHoldStr的比较是错误的。此变量始终为空。要检查文本框中的密码是否与数据模型中的密码匹配,请将txtPass与txttPassword进行比较。

在原始代码中,检查对话框结果。

private void MDiMain_Load(object sender, EventArgs e)
{
setDisplaysize();
Form newLogin = new FormControllers.FrmLogin();
newLogin.StartPosition = FormStartPosition.CenterScreen;
if (newLogin.ShowDialog(this) != DialogResult.OK)
{
Close();
// or better:
// BeginInvoke((Action)Close);
return;
}
// possibly further main form initialization logic here
} 

最新更新