4

I want my formClosing event to cancel its closing operation if the SaveFileDialog, in my SaveAs Click event, is Cancel

void exitToolStripMenuItem_Click (object sender, EventArgs e) {
    this.Close ();
}

void form1_FormClosing (object sender, FormClosingEventArgs e) 
{
    if (isContentChanged) 
    {
        DialogResult result = MessageBox.Show ("Do you want to save [ "+this.Text+"] ?", "Save", MessageBoxButtons.YesNoCancel);
        if (result == DialogResult.Yes) 
        {
            saveAsToolStripMenuItem_Click (sender, e);
        } 
        else if (result == DialogResult.Cancel) 
            e.Cancel = true;
    }
}


private void saveAsToolStripMenuItem_Click (object sender, EventArgs e) 
{
    SaveFileDialog sfd = new SaveFileDialog ();
    sfd.Filter = "Drawing Files | *.drg";
    DialogResult result = sfd.ShowDialog ();
    if (result == DialogResult.OK) {
        SaveFile (sfd.FileName);
        isContentChanged = false;
    } 
    else if (result == DialogResult.Cancel) 
    {
        // NEED TO CANCEL FORM CLOSING HERE   
    }
}

Is it possible? If yes, how?

Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
Naveen Kumar V
  • 2,559
  • 2
  • 29
  • 43

1 Answers1

3

Try this:

private void saveAsToolStripMenuItem_Click (object sender, EventArgs e) 
{
   ...

   if (result == DialogResult.OK) 
   {
       ...         
   } 
   else if (result == DialogResult.Cancel) 
   {  
       ((FormClosingEventArgs) e).Cancel = true; 
   }
}
Salah Akbari
  • 39,330
  • 10
  • 79
  • 109
  • It worked :) . But didn't get whats happening here. Can you explain a bit more? – Naveen Kumar V Oct 28 '15 at 12:21
  • 1
    @NaveenKumarV...Well in the button click you can't set the `e.Cancel` to `true` so you should cast `e` to `FormClosingEventArgs` so that you can access to `Cancel` property. – Salah Akbari Oct 28 '15 at 12:24
  • 1
    @NaveenKumarV...plus to my previous comment:`FormClosingEventArgs` is derived from `CancelEventArgs` and it derived from `EventArgs`. – Salah Akbari Oct 28 '15 at 12:31
  • 1
    @NaveenKumarV When you call `saveAsToolStripMenuItem_Click` from `form1_Closing` you are passing the same `FormClosingEventArgs` as an argument. The method `saveAsToolStripMenuItem_Click` receives it disguised as an `EventArgs` (For further reference, see [Polymorphism](https://msdn.microsoft.com/en-us/library/vstudio/ms173152(v=vs.100).aspx)). The problem is that the type `EventArgs` does not have a property `Cancel` so it's no use to you at all. Downcasting it to `FormClosingEventArgs` will do the job. – Matias Cicero Oct 28 '15 at 12:32
  • 1
    @NaveenKumarV Please note that if the argument `e` is not a disguised `FormClosingEventArgs` the above code will throw a casting exception. – Matias Cicero Oct 28 '15 at 12:33
  • Thank you guys :) Understood!. :) – Naveen Kumar V Oct 28 '15 at 12:38
  • but I am Getting Invalid Cast exception, what can be the problem? – Fardin Behboudi Jun 08 '18 at 10:31