对于学校项目,我被要求创建一个Web浏览器。 在上下文菜单中,我有一个“退出”按钮,它执行一些事情,如将数据上传到SQL数据库等。如果“try”块中有错误,catch块会向用户提供一个问题,如果他想要的话关闭与否。
在“formclosing”事件中,我已经从“退出”按钮连接了我已经存在的“退出”功能,因此如果用户按下红色“X”(在窗口屏幕上)以关闭表单,它将也有同样的效果。
问题在于,因为它是一个“formclosing”事件,即使用户在“退出”按钮的问题对话框中选择“否”,它也会关闭表单。
所以我的问题是如何在“退出”按钮中取消“formclosing”请求?
P.S。 请忽略删除sql命令等奇怪的事情,我们的老师有一些奇怪的请求。假设这确实是所请求的功能。
private void יציאהToolStripMenuItem_Click(object sender, EventArgs e)
{
Favorite fav;
SqlCommand delfav = new SqlCommand("DELETE FROM tblFavorites", conn);
SqlCommand addfav = new SqlCommand("INSERT INTO tblFavorites VALUES (@title, @url)", conn);
addfav.Parameters.Add("@title", SqlDbType.NVarChar, 100);
addfav.Parameters.Add("@url", SqlDbType.NVarChar, 300);
try
{
conn.Open();
delfav.ExecuteNonQuery();
for (int i=0; i<favorites.Items.Count; i++)
{
fav = (Favorite)favorites.Items[i];
addfav.Parameters["@title"].Value = fav.getsettitle;
addfav.Parameters["@url"].Value = fav.getseturl;
addfav.ExecuteNonQuery();
}
Application.Exit();
}
catch
{
DialogResult dialogResult = MessageBox.Show("There was a problem loading your favorites to the database. Do you still wish to quit? \n (All changes to the favorites list will be lost)", "", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
Application.Exit();
}
else
{
//Cancel the formclosing event here!
}
}
finally
{
conn.Close();
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
יציאהToolStripMenuItem_Click(null, null);
}
答案 0 :(得分:1)
您应该替换这两个事件处理程序的功能。另外,您应该使用this.Close()
代替Application.Exit()
private void ToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// your code
try
{
// your code
}
catch
{
DialogResult dialogResult = MessageBox.Show("There was a problem loading your favorites to the database. Do you still wish to quit? \n (All changes to the favorites list will be lost)", "", MessageBoxButtons.YesNo);
if (dialogResult != DialogResult.Yes)
{
//Cancel the formclosing event here!
e.Cancel = true;
}
}
finally
{
conn.Close();
}
}