How to do something if cancel button on save file dialog was clicked?
Asked Answered
A

3

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?

Alcina answered 5/9, 2014 at 20:11 Comment(1)
Add the code to your question showing how you display the Save Dialog Box and when it displays the message box.Accoutre
A
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 */ }
Attitude answered 5/9, 2014 at 20:14 Comment(4)
If I'm not mistaken you can also use DialogResult.CancelShiva
Can confirm this is the best way - also meTarkany
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!Alcina
@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 clarifyJem
J
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");
}
Jem answered 5/9, 2014 at 20:13 Comment(0)
A
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 */ }
Attitude answered 5/9, 2014 at 20:14 Comment(4)
If I'm not mistaken you can also use DialogResult.CancelShiva
Can confirm this is the best way - also meTarkany
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!Alcina
@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 clarifyJem
F
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

Featherstitch answered 22/7, 2022 at 10:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.