使用消息框确定按钮退出事件处理程序



我正在编写一个小的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退出void方法(事件处理程序(:

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

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

最新更新