C# MessageBox dialog result

C#DialogMessagebox

C# Problem Overview


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#?

C# Solutions


Solution 1 - C#

DialogResult result = MessageBox.Show("Do you want to save changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
if(result == DialogResult.Yes)
{ 
    //...
}
else if (result == DialogResult.No)
{ 
    //...
}
else
{
    //...
} 

Solution 2 - C#

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)

Solution 3 - C#

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
}

Solution 4 - C#

This answer was not working for me so I went on to [MSDN](http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox(v=vs.110).aspx "Go to Examples"). 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

Solution 5 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbioxView Question on Stackoverflow
Solution 1 - C#david.sView Answer on Stackoverflow
Solution 2 - C#sczdavosView Answer on Stackoverflow
Solution 3 - C#XtraSimplicityView Answer on Stackoverflow
Solution 4 - C#EddView Answer on Stackoverflow
Solution 5 - C#Greyson StormView Answer on Stackoverflow