How to skip Validating after clicking on a Form's Cancel button

前端 未结 17 1148
一生所求
一生所求 2020-12-08 04:04

I use C#. I have a Windows Form with an edit box and a Cancel button. The edit box has code in validating event. The code is executed every time the edit box loses focus. Wh

相关标签:
17条回答
  • 2020-12-08 04:26

    Obviously CausesValidation property of the button has to be set to false and then the validating event will never happen on its click. But this can fail if the parent control of the button has its CausesValidation Property set to true. Most of the time developers misses/forgets to change the CausesValidation property of the container control (like the panel control). Set that also to False. And that should do the trick.

    0 讨论(0)
  • 2020-12-08 04:27

    Just above the validation code on the edit box add:

    if (btnCancel.focused)
      {
         return;
      }
    

    That should do it.

    0 讨论(0)
  • 2020-12-08 04:27

    This work for me.

    private void btnCancelar_MouseMove(object sender, MouseEventArgs e)
    {
        foreach (Control item in Form.ActiveForm.Controls)
        {
            item.CausesValidation = false;
        }
    }
    
    0 讨论(0)
  • 2020-12-08 04:28

    I found this thread today while investigating why my form would not close when a validation error occurred.

    I tried the CausesValidation = false on the close button and on the form itself (X to close).

    Nothing was working with this complex form.

    While reading through the comments I spotted one that appears to work perfectly

    on the form close event , not the close button (so it will fire when X is clicked also)

    This did the trick.

    AutoValidate = AutoValidate.Disable;
    
    0 讨论(0)
  • 2020-12-08 04:32

    None of these answers quite did the job, but the last answer from this thread does. Basically, you need to:

    1. Insure that the Cancel button (if any) has .CausesValidation set to false
    2. Override this virtual method.

      protected override bool ProcessDialogKey(Keys keyData) {
          if (keyData == Keys.Escape) {
              this.AutoValidate = AutoValidate.Disable;
              CancelButton.PerformClick();
              this.AutoValidate = AutoValidate.Inherit;
              return true;
          }
          return base.ProcessDialogKey(keyData);
      }
      

    I didn't really answer this, just pointing to the two guys who actually did.

    0 讨论(0)
  • 2020-12-08 04:36

    If the validation occurs when the edit box loses focus, nothing about the the cancel button is going to stop that from happening.

    However, if the failing validation is preventing the cancel button from doing its thing, set the CausesValidation property of the button to false.

    Reference: Button.CausesValidation property

    0 讨论(0)
提交回复
热议问题