当单击取消按钮时禁用验证错误提供程序
问题描述:
有没有一种方法可以在单击取消按钮关闭winform时优雅地禁用验证错误提供程序? 验证总是发生在文本框失去焦点时,并且我不希望验证用户何时单击取消按钮,验证用户单击取消时有点愚蠢。当单击取消按钮时禁用验证错误提供程序
答
googling后,找到答案,只需将取消按钮的CauseValidation属性设置为false。而已。
答
我刚碰到这个,我自己设置CauseValidation = false
只是一个部分的解决方案。
当您将Form.CancelButton
设置为取消按钮时,应该使用退出键来调用该按钮。但是,尽管我们设置了CauseValidation = false
,但验证仍会响应“退出”键运行。
为了解决这个问题,添加下面的技巧:
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);
}