views:

61

answers:

2

I have a button click event handler which says this.Close()

In the FormClosing event I detect unsaved changes and say "Do you want to Save?"

If they say Yes I set e.Cancel = true and then call my Save method. If the data is saved ok in my Save method at the end I say this.Close() but the form stays open.

This seems such a simple idea but I can't work it out.

Do I need to create new thread in FormClosing so if they say Yes set e.Cancel = true and create a new thread to do the Save which will then call the this.Close()

+2  A: 

If they say Yes I set e.Cancel = true and then call my Save method. If the data is saved ok in my Save method at the end I say this.Close() but the form stays open

Change this around.

  • Prompt the user
  • If they say yes, set e.Cancel = !Save()
  • If they say no, set e.Cancel = true

This will make the form close unless they say no when prompted, or the Save() routine fails. No new threads or threading is required, just a slight change in the logic.

Reed Copsey
At the moment the Save method does not return a boolean so I will need to do that. Thanks
Jon
Well, you mentioned that save could fail - it'd be just a matter of setting e.Cancel == true if Save fails. Making Save() return a boolean would make this simple, however.
Reed Copsey
+3  A: 

It sounds like what you want to do is NOT set e.Cancel to true, but rather just call Save() conditionally from FormClosing. You only cancel if the save fails. For example:

private void OnFormClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
   if ( IsDataModified() )  // check if the data is unsaved...however you do so
   {
      // display a message asking the user to save changes or abort.
      if(MessageBox.Show("Do you want to save your changes?", 
                         "My Application", 
                         MessageBoxButtons.YesNo) ==  DialogResult.Yes)
      {
          if( !SaveChanges(); )
              e.Cancel = true; // save did not succeed!
      }
   }
}
LBushkin
At the moment the Save method does not return a boolean so I will need to do that. Thanks
Jon
@Jon: Depending on the conditions that could cause Save to succeed/fail, you may also need to add a `try/catch` around the call in `OnFormClosing`. I would not use exceptions as a means of flow control - but it's not desirable to have your app crash with an unhandled exception just as the user is exiting either.
LBushkin