创建一个确认框 c#

3

我遇到了一些问题。虽然我正在慢慢进步并学习新知识,但我对C#仍然很陌生。

现在我有些困惑。我试图创建一个确认框,但它似乎不能像预期的那样工作。

以下是代码:

private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
    MessageBox.Show("Are you sure you want to exit off the application", "Are you sure?", MessageBoxButtons.YesNoCancel); //Gets users input by showing the message box

    if (DialogResult == DialogResult.Yes) //Creates the yes function
    {
        this.Close(); //Exits off the application
    }

    else if (DialogResult == DialogResult.No)
    {
        //Does nothing
    }

1
嗨,查看MessageBox的文档。其中有使用此类的示例。有用的提示:在VisualStudio编辑器中将光标放在MessageBox上,然后按F1键 - 您将被重定向到MessageBox(或其他您放置光标的类)的文档。 - Renatas M.
谢谢,我发现了我的错误。它很明显也很有趣。感谢您的帮助。 - Gulam
2个回答

7
你没有捕获对话框的结果。如果使用了那些if语句,我很惊讶这甚至可以编译通过。(如果不能编译,则说明您真正错过了问题的重要细节。编译器错误值得关注。)
你需要捕获结果:
var result = MessageBox.Show(...);
if (result == DialogResult.Yes)
{
    this.Close();
}
//...

是的,我不确定那是怎么编译通过的。我忘记声明变量并将其分配给消息框了。这是一个愚蠢的错误。 - Gulam

2

Guess this is what you want,

DialogResult result1 = MessageBox.Show("Is Dot Net Perls awesome?",
                                       "Important Question",
                                       MessageBoxButtons.YesNo);

更多细节请查看:https://www.dotnetperls.com/messagebox-show,这里有关于MessageBox.Show()方法的最初回答。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接