C# MessageBox dialog result

2020-05-11 21:20发布

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

5条回答
太酷不给撩
2楼-- · 2020-05-11 21:46

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

查看更多
叛逆
3楼-- · 2020-05-11 21:48

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)
查看更多
爷、活的狠高调
4楼-- · 2020-05-11 21:50

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
}
查看更多
叼着烟拽天下
5楼-- · 2020-05-11 21:59

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;
}
查看更多
Summer. ? 凉城
6楼-- · 2020-05-11 22:01
DialogResult result = MessageBox.Show("Do you want to save changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
if(result == DialogResult.Yes)
{ 
    //...
}
else if (result == DialogResult.No)
{ 
    //...
}
else
{
    //...
} 
查看更多
登录 后发表回答