单击取消按钮时禁用errorprovider的验证

Ben*_*nny 7 errorprovider winforms

有没有办法在点击取消按钮解雇winform时优雅地禁用errorprovider的验证?验证总是在文本框失去焦点时发生,并且我不想在用户单击取消按钮时验证它,当用户单击取消时验证它有点愚蠢.

Ben*_*nny 15

谷歌搜索后,找到答案,只需将取消按钮的CauseValidation属性设置为false.而已.


Ter*_*ver 6

我自己也碰到了这个,设置CauseValidation = false只是部分解决方案.

当您设置Form.CancelButton为取消按钮时,Escape键应该调用该按钮.但是,即使我们设置,它仍然会响应Escape键运行验证CauseValidation = false.

要解决此问题,请添加以下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);
}
Run Code Online (Sandbox Code Playgroud)