Validating Text Box Data Causes Extra LostFocus EventsID: Q96846
|
Using the LostFocus event to validate data in a text box can cause excess LostFocus events after the data is determined invalid and focus is set back to the text box. Setting the focus back to the text box, as is the custom when data is invalid, causes a LostFocus event to occur in the control that just received the focus. If that control is also validating data in its LostFocus event and no data (or invalid data) is entered, that control could set the focus back to itself, triggering a LostFocus event in the text box.
To work around the problem, you need to handle the intended LostFocus event
and ignore those generated as a side-effect of handling invalid data. Using
a Dim Shared variable in Visual Basic for Windows or Visual Basic for
MS-DOS, you can use the LostFocus event to validate text box data. A Dim
Shared variable holding either the TabIndex of the next control to be
validated or a flag indicating that any control can be validated next,
allows you to ignore unintended LostFocus events in other controls.
The example below demonstrates how to use a Dim Shared variable to validate
Text box data in the LostFocus event. The example gives step-by-step
instructions for Visual Basic for Windows, but you can use the exact same
code and controls in Visual Basic for MS-DOS without modification.
Dim Shared Focus As Integer
Function IsValid (t1 As TextBox) As Integer
If t1.Text = "" Then
IsValid = False
Else ' add other data restrictions here
IsValid = True
End If
End Function
Sub Form_Load ()
Focus = -1
End Sub
Sub Text1_LostFocus ()
If Not IsValid(Text1) And (Focus = -1 Or Focus = Text1.TabIndex) Then
MsgBox "Text in Text1 invalid"
Focus = Text1.TabIndex
Text1.SetFocus
Else
Focus = -1
End If
End Sub
Sub Text2_LostFocus ()
If Not IsValid(Text2) And (Focus = -1 Or Focus = Text2.TabIndex) Then
MsgBox "Text in Text2 invalid"
Focus = Text2.TabIndex
Text2.SetFocus
Else
Focus = -1
End If
End Sub
Additional query words: 2.00 3.00 b_vbmsdos
Keywords :
Version :
Platform :
Issue type :
Last Reviewed: June 16, 1999