Microsoft KB Archive/314431

= PRB: Programmatically Changing Focus Does Not Cause Validation =

Article ID: 314431

Article Last Modified on 5/12/2003

-

APPLIES TO


 * Microsoft Visual Basic 6.0 Enterprise Edition
 * Microsoft Visual Basic 6.0 Professional Edition
 * Microsoft Visual Basic 6.0 Learning Edition

-



This article was previously published under Q314431



SYMPTOMS
Code that changes the value of a TextBox or of another control, and then moves the focus to another control where the CausesValidation property is True does not fire the Validate events of the changed control.



CAUSE
This behavior occurs because changing the focus with code does not trigger Validate event.



RESOLUTION
To resolve this behavior, call the ValidateControls method when you change values and focus by the use of code.



STATUS
This behavior is by design.



MORE INFORMATION
By design, if you change the values of controls in code, you must explicitly call ValidateControls to run the Validate events. Validate does not run automatically in this scenario. Similarly, if you close the form after you edit a control without leaving that control, the Validate event does not fire because it does not lose focus. In this case, you can use the QueryUnload event of the Form to decide if ValidateControls should be called.

Steps to Reproduce the Behavior
 Open a new Standard EXE project in Visual Basic 6.0; Form1 is created by default. Add the CommandButton control, Command1, and two TextBox controls, Text1 and Text2, to Form1. CausesValidation is True by default.  Add the following code to the General Declarations section of Form1: Private Sub Command1_Click Dim i As Integer For i = 0 To Controls.Count - 1 If TypeOf Controls(i) Is TextBox Then Controls(i).SetFocus Controls(i).Text = &quot;Hello! &quot; & i       End If    Next i End Sub

Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer) If UnloadMode = vbFormControlMenu Then '       Me.ValidateControls End If End Sub

Private Sub Command1_GotFocus Debug.Print &quot;Command1 got focus&quot; End Sub

Private Sub Text1_GotFocus Debug.Print &quot;Text1 got focus&quot; End Sub

Private Sub Text1_Validate(Cancel As Boolean) Debug.Print &quot;Text1 validate&quot; End Sub

Private Sub Text2_GotFocus Debug.Print &quot;Text2 got focus&quot; End Sub

Private Sub Text2_Validate(Cancel As Boolean) Debug.Print &quot;Text2 validate&quot; End Sub  Press F5 to run the project. Click Command1 and notice the Validate events for the TextBox controls do not fire. Edit the contents of Text2 and then close the form. The Validate event is not fired for Text2.</li> Uncomment the ValidateControls line in the Form_QueryUnload event, run the project, and then repeat step 5; the Validate event fires.</li></ol>

<div class="references_section">