Timothy
Timothy

Reputation: 383

How do I "do something" when a SaveFileDialog is cancelled?

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.

Upvotes: 2

Views: 1852

Answers (1)

Reza Aghaei
Reza Aghaei

Reputation: 125197

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);

Upvotes: 5

Related Questions