I am just adding validation into a new winform. I am using the validating and validated events, in conjunction with an error provider control. Please see code below.
No problem with first validation (ie. if user enters more than 12 characters). Error is set in validating event, and error stays until user enters 12 or less characters. Validated event is then entered and error is reset to empty string.
However, there is a problem with the 2nd validation on same text box. The code checks for zero length in text box.. and sets error with provider. Watching in the debugger, this code is indeed invoked, and error is set ok. Then something weird happens, the validated event is (unexpectedly) fired, and the code there promptly resets the error.
Why is the validated event fired when there is already an error set ? This seems like a .NET bug. Can anyone suggest another way of doing this, or say what I am doing wrong ?
Thanks,
Bazza
Private Sub SampleCodeTextBox_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles SampleCodeTextBox.Validating
If SampleCodeTextBox.Text.Length > 12 Then
e.Cancel = True
FormErrorProvider.SetError(SampleCodeTextBox, "Max of 12 characters for sample code")
End If
If SampleCodeTextBox.Text.Trim.Length = 0 Then
FormErrorProvider.SetError(SampleCodeTextBox, "Must enter a sample code")
End If
End Sub
Private Sub SampleCodeTextBox_Validated(sender As Object, e As System.EventArgs) Handles SampleCodeTextBox.Validated
FormErrorProvider.SetError(SampleCodeTextBox, "")
End Sub
You need to set the
CancelEventArgs.Cancelproperty toTruewhen your zero-length Text check fails in your Validating event handler.From the MSDN article on the Control.Validated Event: