64

I want to make a MessageBox confirmation. Here is the message box:

MessageBox.Show("Do you want to save changes?", "Confirmation", messageBoxButtons.YesNoCancel);

And I want to make something like this (in pseudocode):

if (MessageBox.Result == DialogResult.Yes)
    ;
else if (MessageBox.Result == DialogResult.No)
    ;
else
    ;

How can I do that in C#?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
biox
  • 1,526
  • 5
  • 17
  • 28

5 Answers5

144
DialogResult result = MessageBox.Show("Do you want to save changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
if(result == DialogResult.Yes)
{ 
    //...
}
else if (result == DialogResult.No)
{ 
    //...
}
else
{
    //...
} 
nsgocev
  • 4,390
  • 28
  • 37
david.s
  • 11,283
  • 6
  • 50
  • 82
14

You can also do it in one row:

if (MessageBox.Show("Text", "Title", MessageBoxButtons.YesNo) == DialogResult.Yes)

And if you want to show a messagebox on top:

if (MessageBox.Show(new Form() { TopMost = true }, "Text", "Text", MessageBoxButtons.YesNo) == DialogResult.Yes)
Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167
sczdavos
  • 2,035
  • 11
  • 37
  • 71
  • Yes but on "else if" if i put else if (MessageBox.Show("Text", "Title", MessageBoxButtons.YesNo) == DialogResult.No) the message will re-apear – biox May 27 '12 at 21:01
  • Of course but if you have only two choices Yes/No you have no reason to use else if... – sczdavos May 27 '12 at 21:04
  • Oh ok sry. At least you known this possibility :P That I mainly want to mention is the TopMost property. – sczdavos May 27 '12 at 21:10
9

If you're using WPF and the previous answers don't help, you can retrieve the result using:

var result = MessageBox.Show("Message", "caption", MessageBoxButton.YesNo, MessageBoxImage.Question);

if (result == MessageBoxResult.Yes)
{
    // Do something
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
XtraSimplicity
  • 5,704
  • 1
  • 28
  • 28
2

This answer was not working for me so I went on to MSDN. There I found that now the code should look like this:

//var is of MessageBoxResult type
var result = MessageBox.Show(message, caption,
                             MessageBoxButtons.YesNo,
                             MessageBoxIcon.Question);

// If the no button was pressed ... 
if (result == DialogResult.No)
{
    ...
}

Hope it helps

Edd
  • 1,948
  • 4
  • 21
  • 29
2

Rather than using if statements might I suggest using a switch instead, I try to avoid using if statements when possible.

var result = MessageBox.Show(@"Do you want to save the changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
switch (result)
{
    case DialogResult.Yes:
        SaveChanges();
        break;
    case DialogResult.No:
        Rollback();
        break;
    default:
        break;
}
Greyson Storm
  • 21
  • 1
  • 2