Is there a builtin confirmation dialog in Windows Forms?
Asked Answered
H

3

137

I'd like to create a simple confirm dialog saying "Please check the information and if you're sure it's correct, click OK."

Is there something built in like this?

Hyperboloid answered 2/10, 2010 at 12:28 Comment(0)
M
263

Here is an example. You can try something like this.

var confirmResult =  MessageBox.Show("Are you sure to delete this item ??",
                                     "Confirm Delete!!",
                                     MessageBoxButtons.YesNo);
if (confirmResult == DialogResult.Yes)
{
    // If 'Yes', do something here.
}
else
{
    // If 'No', do something here.
}

You can also try MessageBoxButtons.OKCancel instead of MessageBoxButtons.YesNo. It depends on your requirements.

  1. If you have .Net Framework 4.6 or above please try this.
MessageBoxResult confirmResult = MessageBox.Show("Are you sure to delete this item ??", "Confirm Delete!!", MessageBoxButton.YesNo);`

if (confirmResult == MessageBoxResult.Yes)
{
   // If 'Yes', do something here.
}
else
{
   // If 'No', do something here.
}
Monocarpic answered 4/1, 2013 at 15:38 Comment(3)
This approach worked perfectly for me. I had a case where there is a "reset" button which deletes data and this provides a great method for handling that.Outlive
In my case instead of DialogResult I had to use MessageBoxResultDurand
MessageBoxButtons.YesNo should read MessageBoxButton.YesNo, and DialogResult changes to MessageBoxResult for .NET 4.6.Airless
B
19

MessageBox.Show? You can specify the title, caption, and a few options for which buttons to display.

On the other hand, if you're asking people to confirm information, that sounds like you probably want to show a custom dialog - which you can do with Form.ShowDialog.

Broncho answered 2/10, 2010 at 12:30 Comment(1)
Thanks, I'll look into the Form.ShowDialog class. BTW, how did you edit your question without it showing the revision?Hyperboloid
P
10

In .Net Core you can do it like this:

DialogResult dialogResult= MessageBox.Show("Are you sure to delete?", "Confirm", MessageBoxButtons.YesNo);

if (dialogResult == DialogResult.Yes)
{
    //if code here....            
}
else
{
   //else code here.... 
}

Output Result

Pig answered 26/7, 2020 at 13:58 Comment(1)
Actually that example is .Net 2.x, 3.x and 4.x and not .Net Core. In .Net Core you cannot create WinForms. From .Net Core 3.0 you have the XAML option though, but I am not sure you create Message Boxes the same way.Queensland

© 2022 - 2024 — McMap. All rights reserved.