我有一个winforms应用程序,通过在登录前检查用户权限,用户名和密码是否匹配来登录用户。数据库目前只有三个用户用于测试目的。
我面临的问题是,每当我尝试登录时,程序会在登录前冻结至少30秒。我已经到处寻找解决方案。我试过一个背景工作者,但对我来说也不行;也许我错了。
这是用于登录的代码
frmLogins.cs
private void btnLogin_Click(object sender, EventArgs ev)
{
try
{
SqlDataAdapter sda = new SqlDataAdapter("Select count(*) from Logins where Username='" + txtUserName.Text + "' and Password='" + txtPassword.Text + "' and Type='" + cbType.Text + "'", scon);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
sda1 = new SqlDataAdapter("Select Type from Logins where Username='" + txtUserName.Text + "' and Password='" + txtPassword.Text + "'", scon);
dt1 = new DataTable();
sda1.Fill(dt1);
//Check if user matches with admin then log them in
if (dt1.Rows[0][0].ToString() == "Admin")
{
lblMessage.Text = "Logging Successful!";
SnackBarTimer();
Hide();
AdminForm admin = new AdminForm();
admin.Show();
}
//Check if user matches with secretary then log them in
if (dt1.Rows[0][0].ToString() == "Secretary")
{
lblMessage.Text = "Logging Successful!";
SnackBarTimer();
Hide();
frmMain main = new frmMain();
main.Show();
}
//Check if user matches with employee then log them in
if (dt1.Rows[0][0].ToString() == "Employee")
{
}
lblMessage.Text = "Logging In...";
SnackBarTimer();
}
}
catch (Exception ex)
{
lblMessage.Text = ex.Message;
SnackBarTimer();
}
finally
{
scon.Close();
}
}
答案 0 :(得分:0)
我无法消除延迟,但是我想出了如何正确实现背景工作者,所以现在形式不再冻结。我还添加了一个进度条来显示某种形式的进展。
登录按钮单击“事件:
”private void btnLogin_Click(object sender, EventArgs ev)
{
//
//If background worker busy, show snackbar and login after
//
if (!bgw.IsBusy)
{
pnlSnackBar.Visible = true;
lblMessage.Text = "Logging In...Please wait";
SnackBarTimer();
bgw.RunWorkerAsync();
}
}
BackgroundWorker的:
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
try
{
cmd = new SqlCommand("Select Type from Logins where Username='@user' and Password='@pass'", scon);
cmd.Parameters.AddWithValue("@user", txtUserName.Text);
cmd.Parameters.AddWithValue("@pass", txtPassword.Text);
sda1 = new SqlDataAdapter(cmd);
dt1 = new DataTable();
sda1.Fill(dt1);
}
catch (Exception ex)
{
//pnlSnackBar.Visible = true;
lblMessage.Text = ex.Message;
SnackBarTimer();
}
}
BackgroundWorker已完成:
private void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
try
{
if (dt1.Rows.Count == 1)
{
if (dt1.Rows[0][0].ToString() == "Admin")
{
LoginInfo.UserID = txtUserName.Text;
Hide();
AdminForm admin = new AdminForm();
admin.Show();
}
if (dt1.Rows[0][0].ToString() == "Secretary")
{
LoginInfo.UserID = txtUserName.Text;
Hide();
frmMain main = new frmMain();
main.Show();
}
if (dt1.Rows[0][0].ToString() == "Employee")
{
LoginInfo.UserID = txtUserName.Text;
Hide();
EmployeeForm employee = new EmployeeForm();
employee.Show();
}
}
}
catch (Exception ex)
{
pnlSnackBar.Visible = true;
lblMessage.Text = ex.Message;
SnackBarTimer();
}
}
改进进度:
private void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
metroProgressSpinner.Value = e.ProgressPercentage;
}