Disable validation on ESC key

Problem:
There are a TextBox and a Button on the form,the Button is set to the CancelButton of Form. TextBox.CancelValidation
property is set to true, while Button.CancelValidation is set to false. When clicked on Button the validation is not performed and form closes successfully but pressing ESC key does not close the Form.
Clicking on the button doesnot trigger validation event and will close the Form because button is set to CauseValidation equals to false. But Pressing ESC key doesnot close the Form it triggers the Validating Event.

Workaround

To fix this problem, you may intercept the ESC key explicitly and
set AutoValidate property to AutoValidate.Disable to disable the
validating, sample code snippet is listed below:

VB

Protected Overrides Function ProcessDialogKey(ByVal keyData As
System.Windows.Forms.Keys) As Boolean
Dim cancel As Button = CType(Me.CancelButton, Button)
If keyData = Keys.Escape Then
Me.AutoValidate = Windows.Forms.AutoValidate.Disable
cancel.PerformClick()
Me.AutoValidate = Windows.Forms.AutoValidate.Inherit
Return True
End If
Return MyBase.ProcessDialogKey(keyData)
End Function

C#

protected override bool ProcessDialogKey(Keys keyData)
{
if (keyData == Keys.Escape)
{
Button close = (Button)CancelButton;
AutoValidate = System.Windows.Forms.AutoValidate.Disable;
close.PerformClick();
AutoValidate = System.Windows.Forms.AutoValidate.Inherit;
return true;
}
return base.ProcessDialogKey(keyData);
}
, , , , ,

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Share to Facebook Share to Twitter Stumble It Share on Tumblr Digg More...