Reputation: 49
I am working with the FormClosing
event
DialogResult dg = MessageBox.Show("Do you want to save changes?", "Closing", MessageBoxButtons.YesNoCancel);
if (dg == DialogResult.Yes)
{
saveToolStripMenuItem_Click(sender, e);
}
else if (dg == DialogResult.Cancel)
{
e.Cancel = true;
}
This code works perfectly, when I click on the X to close the Form:
Above is 100% correct, however, once the save dialog is presented, when I click on Cancel button inside the save dialog, it still closes the form - it should also return?
Upvotes: 2
Views: 3780
Reputation: 23732
As already suggested by Matthew Watson you can create a helping method. Here is a short version of it:
private DialogResult SaveStuff()
{
return new SaveFileDialog().ShowDialog();
}
This can be used in the saveToolStripMenuItem_Click
event like this:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult dr = SaveStuff();
if (dr == DialogResult.OK)
{
// ...
}
}
But most importantly you can use it in the FormClosing
event and check for the return value:
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dg = MessageBox.Show("Do you want to save changes?", "Closing", MessageBoxButtons.YesNoCancel);
if (dg == DialogResult.Yes)
{
if (SaveStuff() == DialogResult.Cancel)
{
e.Cancel = true;
}
}
else if (dg == DialogResult.Cancel)
{
e.Cancel = true;
}
}
This way the Form should remain unclosed when hitting the cancel button on the SaveFileDialog
Upvotes: 2