如何在WinForms MessageBox按钮上实现事件处理程序

4
我有一个WinForms应用程序,在所有字段都输入完毕后,会出现一个保存按钮。
点击保存按钮时,会弹出一个消息框,显示“记录成功保存”。消息框上有两个按钮:“是”和“否”。
如果选择“是”,则应该保存记录并清除表单上的所有字段。如果选择“否”,则应该在不保存记录的情况下清除表单上的所有字段。
如何实现这个功能?

4
Stackoverflow 不是一个免费的代码编写服务。请展示你已经尝试了一些东西。 - Benjamin Gale
2
太好了,你遇到什么问题了? - Kevin Brydon
6
你忘记了提问。 - I4V
1
获取 MessageBox.ShowDialog 的结果,以查看是否点击了“是”或“否”,并根据该结果采取相应的操作,这不需要事件处理程序。 - mtijn
3个回答

25
你不需要一个事件处理程序;MessageBox类的Show方法返回一个DialogResult。
DialogResult result = MessageBox.Show("text", "caption", MessageBoxButtons.YesNo);
if(result == DialogResult.Yes){
   //yes...
}
else if(result == DialogResult.No){
   //no...
}

3

有一个名为DialogResult的枚举可以处理此类事情(来源于MSDN

private void validateUserEntry5()
{
    // Checks the value of the text.
    if(serverName.Text.Length == 0)
    {
        // Initializes the variables to pass to the MessageBox.Show method.
        string message = "You did not enter a server name. Cancel this operation?";
        string caption = "No Server Name Specified";
        MessageBoxButtons buttons = MessageBoxButtons.YesNo;
        DialogResult result;
        // Displays the MessageBox.
        result = MessageBox.Show(this, message, caption, buttons);
        if(result == DialogResult.Yes)
        {
            // Closes the parent form.
            this.Close();
        }
    }
}

2
您可以使用 DialogResult 枚举 来实现此功能。
if(MessageBox.Show("Title","Message text",MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//do something
}

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