The Validating Event | | Back in the good old days, life was a lot different. If you wanted to make sure the user entered what you wanted them to, you only had a few events to trap. VB6 changed this with its Validating event. Well, Gasp, if you need to validate user data (and you don't have a bound control to do it for you), Validating is the event for you.
Basically, it looks at the code you write in the event handler and if it doesn't pass your test, it barks and sticks the user back in that control until they get it right. What could be better than this, right?
So, before I continue, let me walk you through what events occur when you Enter or Leave a TextBox Control:
1) Enter
2) GotFocus
3) Leave
4) Validating
5) Validated
6) LostFocus
Now, I know it might be a little awkwardlly worded. These are the events that occur when you Enter a TextBox and then leave. It's not to say that every time you Enter a TextBox you immediately fire events 3-6. Overall though, this is the sequence that things happen. Remember that if you try to close the form once the control has focus and it fails validation, it won't let you leave. So you'll want to play with e.Cancel depending on your situation (after all, you don't want to bark at a user if they press F1 to receive Context Sensitive Help b/c they can't figure out what to do.
Private Sub TextBox1_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles
TextBox1.Validating
'I'm checking that the Text.Length is Greater than 0, but any rule you want
'should be substituted
If Not TextBox1.Text.Length > 0 Then
'Insert Message here or Fire off an error Provider
e.Cancel = True
End If
End Sub |
Well, like everything else, the more you understand something, the better time you'll have working with it. |