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

前端 未结 17 1202
一生所求
一生所求 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:36

    I was having problems getting my form to close, since the validation of certain controls was stopping it. I had set the control.CausesValidation = false for the cancel button and all the parents of the cancel button. But still was having problems.

    It seemed that if the user was in the middle of editing a field that was using validation and just decided to give up (leaving the field with an invalid input), the cancel button event was being fired but the window would not close down.

    This was fixed by the following in the cancel button click event:

    private void btnCancel_Click(object sender, EventArgs e)
    {
        // Stop the validation of any controls so the form can close.
        AutoValidate = AutoValidate.Disable;
        Close();
    }
    

提交回复
热议问题