Textbox Enter event fires twice

brosmi

New member
Joined
Feb 21, 2008
Messages
2
Programming Experience
10+
I have 3 textboxes on a form (txt1,txt2,txt3)

I am using an event handler (EnterHandler) to handle each textbox's Enter
event for Validation.

In the EnterHandler for txt3 I will validate that txt2 contains a Y and if not I will set the focus back to txt2.

The focus goes to txt2 but why does the Enter event get invoked twice for txt2. ?


Private Sub EnterHandler(ByVal sender As Object, ByVal e As System.EventArgs) Handles txt1.Enter, txt2.Enter, txt3.Enter
Debug.Print("ENTER " & sender.name)
Select Case sender.name
Case "txt3"
If txt2.Text <> "Y" Then
MsgBox("txt2 must be Y")
txt2.Focus()
End If
End Select
End Sub

Immediate Window Output

ENTER txt1
ENTER txt2
ENTER txt3
ENTER txt2
ENTER txt2
 
bc you focused it, the Enter event documentation is very clear about this. Validating event would be my first choice if I wanted to validate something.
 
When I set the focus to txt2 in the EnterHandler procedure it triggers the EnterHandler for txt2 twice. Surely it should only trigger it once.

Here is a brief background to this.

I have developed many screens over the years in VB6 which must validate data according to the following rules.

1) Only validate a textbox as I move forward through controls. (i.e. tab forward or click into another textbox with a higher tabindex).

2) No validation on a textbox if I enter garbage and click or tab to an earlier control.

3) If I move from textbox2 to textbox7 then I must validate all textboxes in between the two controls. (i.e. from 2 to 6). If validation fails on any of these
textboxes I will display a message and set the focus to the offending textbox.

In VB6 I used the gotfocus event to handle my validation. One reason is that I know whether the user has just moved forwards or backwards.

In vb.net I have tried using Gotfocus & Enter events. The Enter event works other than triggering the Enter event twice if I issue a .Focus statement to set the focus to a textbox which has failed validation.

The Gotfocus event continues to set the focus to the textbox the user tabbed to or clicked to even I call a .focus statement to Setfocus to another textbox.
 
Back
Top