C# MessageBox 对话框结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10777123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# MessageBox dialog result
提问by biox
I want to make a MessageBox confirmation. Here is the message box:
我想做一个 MessageBox 确认。这是消息框:
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# 中做到这一点?
采纳答案by david.s
DialogResult result = MessageBox.Show("Do you want to save changes?", "Confirmation", MessageBoxButtons.YesNoCancel);
if(result == DialogResult.Yes)
{
//...
}
else if (result == DialogResult.No)
{
//...
}
else
{
//...
}
回答by sczdavos
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)
回答by Edd
This answer was not working for me so I went on to MSDN. There I found that now the code should look like this:
这个答案对我不起作用,所以我继续访问MSDN。在那里我发现现在代码应该是这样的:
//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
希望能帮助到你
回答by XtraSimplicity
回答by Greyson Storm
Rather than using if statements might I suggest using a switch instead, I try to avoid using if statements when possible.
我建议使用 switch 代替使用 if 语句,我尽量避免使用 if 语句。
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;
}

