在表单加载时,我试图查看我的应用程序是否可以连接到数据库。如果它没有连接我想显示一个带有好消息的消息框,并关闭应用程序。我遇到的问题是,当它试图关闭应用程序时,它会触及Form_closing事件,询问他们"他们是否想要退出应用程序"对于无权访问应用程序/数据库的用户来说,查看消息框看起来有点奇怪。我只是想跳过表格结束活动,只是关闭表格,任何帮助将不胜感激。
private void Form1_Load(object sender, EventArgs e)
{
checkcon();
}
private void checkcon()
{
try
{
MSSQL.SqlConnection con = new MSSQL.SqlConnection(constr);
con.Open();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Your domain account does not have sufficient privilages to continue with the application please contact the IS support Team.");
Close();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult result = MessageBox.Show("Are you sure you want to exit the application?", "Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.No)
{
e.Cancel = true;
}
else
{
}
}
答案 0 :(得分:2)
添加一个静态bool var作为检查是否显示Dialogue:
public static bool HasPermission=true;
private void checkcon()
{
try
{
MSSQL.SqlConnection con = new MSSQL.SqlConnection(constr);
con.Open();
con.Close();
}
catch (Exception ex)
{
HasPermission=false;
MessageBox.Show("Your domain account does not have sufficient privilages to continue with the application please contact the IS support Team.");
Close();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{ if (HasPermission)
{
DialogResult result = MessageBox.Show("Are you sure you want to exit the application?", "Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.No)
{
e.Cancel = true;
}
else
{
}
}
}
答案 1 :(得分:0)
我认为这很容易。
只需创建boolean类型的变量并检查用户是否可以访问数据库?如果没有,请在没有任何确认的情况下关闭它。
让我通过修改你的代码来解释你:
bool userGotPermissionToYourApplication = true;
private void Form1_Load(object sender, EventArgs e)
{
checkcon();
}
private void checkcon()
{
try
{
MSSQL.SqlConnection con = new MSSQL.SqlConnection(constr);
con.Open();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Your domain account does not have sufficient privilages to continue with the application please contact the IS support Team.");
userGotPermissionToYourApplication = false;
Close();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(userGotPermissionToYourApplication)
{
DialogResult result = MessageBox.Show("Are you sure you want to exit the application?", "Alert", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.No)
{
e.Cancel = true;
}
else
{
}
}
}