disable validation of errorprovider when click cancel button

冷暖自知 提交于 2019-12-01 16:02:07

问题


is there a way to disable the validation of errorprovider elegantly when click cancel button to dismiss a winform? The validation always happens when the textbox lose focus, and i don't wanna it to validate when the user click cancel button, it is just a little bit silly to validate when the user clicking cancel.


回答1:


after googling, found the answer, just set CauseValidation property of the cancel button to false. that's it.




回答2:


I just ran into this myself and setting CauseValidation = false is only a partial solution.

When you set the Form.CancelButton to the cancel button, the Escape key is supposed to invoke that button. It does, however, validation still runs in response to the Escape key, even though we set CauseValidation = false.

To fix it, add the following hack:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    // Although we set CausesValidation = false for the Cancel button,
    //  the Escape key fails to cancel due to validation failure. The
    //  Form.CancelButton property should invoke the validation-free
    //  cancel button, but doesn't. Force the issue here.
    if (keyData == Keys.Escape)
    {
        DialogResult = DialogResult.Cancel;
        return true;
    }
    return base.ProcessCmdKey(ref msg, keyData);
}


来源:https://stackoverflow.com/questions/1995213/disable-validation-of-errorprovider-when-click-cancel-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!