2

NB: The answer in this question is out of date.


So, I have a save dialog box:

...
SaveFileDialog sfd = new SaveFileDialog();
sfd.ShowDialog();

// SaveFileDialog.[Whatever] - Init code basically.

if (sfd.DialogResult == DialogResult.OK)
    {
        // Definitely do something.
        Console.Print("File selected.");
    }
if (sfd.DialogResult == DialogResult.Abort)
    {
        // Maybe the opposite of the above?
        Console.Print("File selection Cancelled");
    }
if ( ... ) { }
    and so on.

But... SaveFileDialog.DialogResult has been replaced by events instead...

And that the only available events are SaveFileDialog.FileOK, SaveFileDialog.Disposed and SaveFileDialog.HelpRequest.

How do I trigger an event (or move to a line of code) based when the user clicked Cancel rather than completing it (Clicking Save)?

I'm looking to branch based on whether the user cancels or successfully selects the file location to save to.

Community
  • 1
  • 1
Timothy
  • 364
  • 1
  • 12
  • 24
  • 1
    You can check the result of `yourSaveFileDialog.ShowDialog()` – Reza Aghaei Oct 09 '15 at 03:24
  • 3
    It is incorrect to say the DialogResult has been replaced, the MSDN code example shows this is still working. https://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog%28v=vs.110%29.aspx – David Oct 09 '15 at 03:45

1 Answers1

5

Working with DialogResult is not deprecated and also those events are not something new.
To perform an action for Cancel, you can create your SaveFileDialog and configure it, you can call ShowDialog and then check the result:

var sfd= new SaveFileDialog();
//Other initializations ...
//sfd.Filter= "Text files (*.txt)|*.txt|All files (*.*)|*.*";
//sfd.DefaultExt = "txt";

if(sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    MessageBox.Show("Save Clicked");
    //ِDo something for save
}
else
{
    MessageBox.Show("Cancel Clicked");
    //Do something for cancel
}

You can access to selected file using FileName property, for example MessageBox.Show(sfd.FileName);

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • "SaveFileDialog.DialogResult has been replaced by events instead..", it appeared that the OP does not wish to use DialogResult? – David Oct 09 '15 at 03:46
  • 1
    @David: there's no good reason to do that over this method. Sure, if the OP wants to do it the hard way, they are free to build machinery to deal with that. I don't see why we should pander to that. – siride Oct 09 '15 at 03:53
  • 1
    I agree, see my comments for the OP. – David Oct 09 '15 at 03:54
  • Good answer solved my problem http://stackoverflow.com/questions/40818152/savefiledialog-is-throwing-indexoutofrangeexception-when-canceled – Ryu Nov 26 '16 at 13:10