阻止对话框关闭按钮的单击事件处理程序

qst*_*ter 63 .net c# windows winforms

我有一个与我一起展示的对话框<class>.ShowDialog().它有一个OK按钮和一个Cancel按钮; OK按钮也有一个事件处理程序.

我想在事件处理程序中进行一些输入验证,如果失败,则通过消息框通知用户并阻止对话框关闭.我不知道怎么做最后一部分(防止关闭).

Arj*_*jan 139

您可以通过设置窗体的取消收DialogResultDialogResult.None.

button1是AcceptButton的示例:

private void button1_Click(object sender, EventArgs e) {
  if (!validate())
     this.DialogResult = DialogResult.None;
}
Run Code Online (Sandbox Code Playgroud)

当用户点击按钮1和验证方法返回false,形式不会被关闭.

  • 由于AcceptButton 是button1,因此单击时DialogResult 始终设置为DialogResult.OK。 (2认同)

Chr*_*isF 45

鉴于您已指定需要弹出错误对话框,一种方法是将验证移动到OnClosing事件处理程序中.在此示例中,如果用户对对话框中的问题回答"是",则表单关闭将中止.

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...
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

通过设置,e.Cancel = true您将阻止表单关闭.

但是,以内联方式显示验证错误(通过以某种方式突出显示有问题的字段,显示工具提示等)并防止用户首先选择"确定"按钮将是更好的设计/用户体验.


Han*_*ant 16

不要为此使用FormClosing事件,您将希望允许用户通过取消或单击X来关闭对话框.只需实现OK按钮的Click事件处理程序,并且在您满意之前不要关闭:

private void btnOk_Click(object sender, EventArgs e) {
  if (ValidateControls())
    this.DialogResult = DialogResult.OK;
}
Run Code Online (Sandbox Code Playgroud)

"ValidateControls"是您的验证逻辑.如果出现问题,则返回false.

  • 一个较小的细节-假定您没有在“确定”按钮的设计时设置中指定DialogResult:确定。 (2认同)