7

I am using c# WinForms. I have a save dialog box that pops up and a message box after that that says it was saved successfully.

I just realized that if a user clicks cancel, my message box still comes.

How do i tell when a user clicks the cancel button on a save dialog box and then do something when it is cancelled?

Amir
  • 714
  • 1
  • 13
  • 37
jAC
  • 3,155
  • 3
  • 18
  • 29
  • 2
    Add the code to your question showing how you display the Save Dialog Box and when it displays the message box. – Black Frog Sep 05 '14 at 20:15

3 Answers3

17

Use DialogResult

if (form.ShowDialog() == DialogResult.Cancel)
{
    //user cancelled out
}

For SaveFileDialog:

SaveFileDialog saveFileDialog = new SaveFileDialog();
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
    MessageBox.Show("your Message");
}
Habib
  • 219,104
  • 29
  • 407
  • 436
13

A save dialog box after closing has the DialogResult property set to what happens. In your case:

if (mySaveDialog.DialogResult == DialogResult.OK) { /* show saved ok */ }
plinth
  • 48,267
  • 11
  • 78
  • 120
  • If I'm not mistaken you can also use DialogResult.Cancel – Andrew Grinder Sep 05 '14 at 20:15
  • Can confirm this is the best way - also me – jordan Sep 05 '14 at 20:15
  • It wouldn't let me do mySaveDialog.DialogResult but Habib's answer below worked great! (same thing really just a typo i think) Thank yo so much! – jAC Sep 05 '14 at 20:26
  • 1
    @jordan.peoples, There is nothing wrong with my answer and also it was posted first (almost 30 seconds earlier). I am fine with the accept, just wanted to clarify – Habib Sep 05 '14 at 22:43
0

In case you are using WPF in a open file dialog, the better option I found is to store the selected file path (File.ReadAllText(filedialog.Filename) ) in a string and then check if its !== null wich means the user has a file selected. If the file path is null so the file is empty or the user just clicked on cancel button