The technique discussed in this
section is no longer recommended with VB6. Here
we outline the technique without going into
details of implementation.
In order to "pull back"
the focus to a control that has a validation
problem, VB6 uses the Validate event and the
CausesValidate property as discussed in previous
sections.
However, in versions of VB before VB6 the Validate event and
CausesValidate property did not exist for standard controls such as the Textbox.
In earlier versions of VB, a technique for retaining focus on a control was:
-
Perform a validation check in the LostFocus
event procedure.
-
If the validation fails, call the control's
SetFocus method to keep focus on the control.
Although the technique sounds
simple enough, there were a number of complicating
factors that the programmer had to take into
account: Because the system was between two
controls, calling the SetFocus method of the
control being validated could cause the LostFocus
event of a second control to fire. What if the
second control in turn had similar validation
code in its LostFocus event procedure? If there
were a validation failure in the second control
as well, then the second control would also
try to "grab" focus back from the
first control.
The first control in turn would
fire its LostFocus event a second time, and
so on, in an infinite loop. To handle this problem
of the dueling LostFocus event procedures, it
was necessary to put a global flag variable
in the application that would be set during
a LostFocus event procedure's validation.
In that way, other controls' validation
code could check this flag and would not run
if another control's validation were already
pending.
A second problem was caused by
the fact that there were some controls (such
as Cancel CommandButtons, for example) that
should always be allowed to receive focus from
another control on the form even if there were
a validation problem. Thus, it would be necessary
to put more logic in validation routines to
ignore the validation logic if the proposed
target control were always allowed to receive
focus.
If the above seems less than
robust or overly complex to you, you are not
alone in your opinion. In the release of VB6,
Microsoft heeded the desires of many VB programmers
and provided the Validate event and the CausesValidation
property (see the previous sections in this
chapter) to put a stop to control validation
madness.
The GotFocus/LostFocus technique just discussed in this section
is therefore no longer necessary or recommended.
Other Field-Level Validation Techniques topics