$ P $的关闭按钮的单击事件处理程序pventing对话单击、按钮、事件、程序

2023-09-03 05:35:12 作者:`過祛

我有我秀与℃的对话框;类> .ShowDialog()。它有一个确定按钮和一个取消按钮; OK按钮也有一个事件处理程序。

I have a dialog that I show with <class>.ShowDialog(). It has an OK button and a Cancel button; the OK button also has an event handler.

我想在事件处理程序的一些输入验证,如果失败,通知有一个消息框和prevent从关闭该对话框的用户。我不知道该怎么办的最后一部分(preventing收盘)。

I want to do some input validation in the event handler and, if it fails, notify the user with a message box and prevent the dialog from closing. I don't know how to do the last part (preventing the close).

推荐答案

既然你已经指定你想有一个弹出错误对话框的,这样做的一种方法是您验证移动到OnClosing事件处理程序。在这个例子中,表单关闭时,如果用户回答是肯定的对话框中的问题,一个中止。

Given that you've specified you want a pop error dialog, one way of doing this is to move your validation into a OnClosing event handler. In this example the form close is a aborted if the user answers yes to the question in the dialog.

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
   // Determine if text has changed in the textbox by comparing to original text.
   if (textBox1.Text != strMyOriginalText)
   {
      // Display a MsgBox asking the user to save changes or abort.
      if(MessageBox.Show("Do you want to save changes to your text?", "My Application",
         MessageBoxButtons.YesNo) ==  DialogResult.Yes)
      {
         // Cancel the Closing event from closing the form.
         e.Cancel = true;
         // Call method to save file...
      }
   }
}

通过设置 e.Cancel = TRUE 您将prevent形式的关闭。

By setting e.Cancel = true you will prevent the form from closing.

然而,这将是一个更好的设计/用户体验来显示验证错误的内联(通过突出显示有问题的领域,在某种程度上,显示工具提示等)的和$ P $从首先选择确定按钮pvent用户。

However, it would be a better design/user experience to display the validation errors inline (via highlighting the offending fields in some way, displaying tooltips, etc.) and prevent the user from selecting the OK button in the first place.