Suzanne Coetzee
Suzanne Coetzee

Reputation: 49

C# Windows Forms FormClosing event

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:

  1. CANCEL will return to the form without any changes made
  2. NO will close the form instantly
  3. YES will open the save dialog

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

Answers (1)

Mong Zhu
Mong Zhu

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

Related Questions