C# 消息框按钮上的事件处理程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16334323/
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
Event handlers on Message box buttons
提问by Kaushik27
I have a winform application. Where when all fields are entered there is a save button. On the click of save button a messagebox appears record saved successfully. The messagebox has 2 buttons 'yes' and 'no'. If yes then the record should be saved and all the fields on the form should be cleared and if no is clicked then all the fields should be cleared on the form without the record getting saved.
我有一个 winform 应用程序。输入所有字段时,有一个保存按钮。单击保存按钮时,会出现一个消息框,记录已成功保存。消息框有 2 个按钮“是”和“否”。如果是,则应保存记录并清除表单上的所有字段,如果单击否,则应清除表单上的所有字段,而不保存记录。
采纳答案by Omar
The Show method of the MessageBox class returns a DialogResult:
MessageBox 类的 Show 方法返回一个 DialogResult:
DialogResult result = MessageBox.Show("text", "caption", MessageBoxButtons.YesNo);
if(result == DialogResult.Yes){
//yes...
}
else if(result == DialogResult.No){
//no...
}
回答by bash.d
There is DialogResult-enum to handle such things (from MSDN)
有DialogResult-enum 来处理这些事情(来自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();
}
}
}
回答by Arshad
You can use DialogResult Enumerationfor this.
您可以为此使用DialogResult 枚举。
if(MessageBox.Show("Title","Message text",MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//do something
}

