【问题标题】:Exit event handler with MessageBox OK button使用 MessageBox OK 按钮退出事件处理程序
【发布时间】:2019-12-22 19:02:27
【问题描述】:

我正在编写一个小型 winforms 应用程序,并且我有一个附加到按钮的事件处理程序。在BtnOk_click 事件中,如果文本框的值为 "" 或者它具有默认值,我会检查条件并显示一个消息框。 我正在努力寻找在关闭消息框后退出事件的方法。

我尝试使用 Close(),但我不想关闭整个表单,只是为了退出事件处理程序。

private void BtnOK_Click(object sender, FormClosingEventArgs e) 
 //when the user presses the OK button on the GUI
{
    pcName = txtBoxPcName.Text;
    if((pcName == "") || (pcName == "PC Name"))
    {
        MessageBox.Show("Computer name cannot be \"" + pcName + "\". \nPlease enter a valid computer name!");
        if (DialogResult == DialogResult.OK)
        {
            //how do I exit the event handler and return back to my main form?
        }
    }
    else
    {

    }
    ... // some other code continues here
}

在我按下消息框上的 OK 按钮后,代码继续超出 else{} else 条件。

【问题讨论】:

  • 只是做一个return;
  • 最好在输入有效之前禁用“确定”按钮,而不是发布消息。然后在 UI 上明确说明有效文本应该是什么。

标签: c# winforms


【解决方案1】:

您可以只使用return 退出您的void 方法(事件处理程序):

if (DialogResult == DialogResult.OK)
{
    return;
}

参考:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/return

【讨论】:

    猜你喜欢
    • 2013-03-05
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多