我的表单包含一个名为button
的{{1}}。我只是将下面的代码放在关闭按钮中,单击...然后第二个代码集用于表单关闭。但是,如果我在单击close
close
时执行此操作,则会出现button
。当我单击“是” 按钮时,该表单没有关闭,但是如果我第二次单击“是” 按钮,则该表单将关闭。关闭。是什么原因?你能帮我吗?
MessageBox
答案 0 :(得分:6)
请勿关闭/退出Application
,而是关闭Form
:
private void btnClose_Click(object sender, EventArgs e) {
// On btnClose button click all we should do is to Close the form
Close();
}
private void frminventory_FormClosing(object sender, FormClosingEventArgs e) {
// If it's a user who is closing the form...
if (e.CloseReason == CloseReason.UserClosing) {
// ...warn him/her and cancel form closing if necessary
e.Cancel = MessageBox.Show("Are You Sure You Want To Close This Form?",
"Close Application",
MessageBoxButtons.YesNo) != DialogResult.Yes;
}
}
编辑:通常,我们向用户询问直接问题(不清楚如果我只是表格” ),例如
private void frminventory_FormClosing(object sender, FormClosingEventArgs e) {
// Data has not been changed, just close without pesky questions
if (!isEdited)
return;
// If it's a user who is closing the form...
if (e.CloseReason == CloseReason.UserClosing) {
var action = MessageBox.Show(
"You've edited the data, do you want to save it?"
Text, // Let user know which form asks her/him
MessageBoxButtons.YesNoCancel);
if (DialogResult.Yes == action)
Save(); // "Yes" - save the data edited and close the form
else if (DialogResult.No == action)
; // "No" - discard the edit and close the form
else
e.Cancel = true; // "Cancel" - do not close the form (keep on editing)
}
}
答案 1 :(得分:0)
所以,因为我无法发表评论,所以我会做这样的事情。
//Create this variable
private bool _saved = true;
public Form1()
{
InitializeComponent();
}
private void btnSave_Click(object sender, EventArgs e)
{
DoSomething();
_saved = true;
}
//Raised when the text is changed. I just put this for demonstration purpose.
private void textBox1_TextChanged(object sender, EventArgs e)
{
_saved = false;
}
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (_saved == false)
{
var result = MessageBox.Show("Are you sure you want to close?\nYou may have unsaved information", "Information", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
_saved = true;
Application.Exit();
}
else
e.Cancel = true;
}
}
希望这可以解决您的问题