Why doesn't my SetFocus work?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Petrol
    Contributor
    • Oct 2016
    • 283

    Why doesn't my SetFocus work?

    I have several forms containing bound controls in which a phone number is to be entered. Because I want the saved text string to include spaces here and there (e.g. 07 1234 5678 for land lines, or 0412 345 678 for mobiles), I have a function which reformats the given text string. Since the control is bound to the requisite control source, the reformatted phone number is automatically stored in the record. The function is called from the AfterUpdate procedure of the control, and works well.
    If, however, the user enters an invalid string (e.g. nonnumeric characters, or wrong number of digits), the functon outputs an error message asking the user to re-enter it, and returns the word "Invalid". To avoid the risk of the user missing the message and moving on, I then want to keep the focus on the same control. However the SetFocus command doesn't work (or perhaps it works but then is immediately overridden) and the focus moves to control with the the next tab stop. Is there any way I can fix this? (The control is, of course, enabled and unlocked).
    Code:
    Private Sub txtHome_phone_AfterUpdate()
    '
    '   Checks  and standardises format of home phone numbers.  It will accept them either with or without area codes.
    '
    Me!txtHome_phone = Nz(FixPhoneNum(Me!txtHome_phone))
    If Me!txtHome_phone = "Invalid" Then
        Me!txtHome_phone.SetFocus           '  Unfortunately, this doesn't work and I don't know why  :-(
    End If
    
    Exit Sub
    End Sub
  • NeoPa
    Recognized Expert Moderator MVP
    • Oct 2006
    • 32654

    #2
    Hi Petrol.

    Without answering directly for now, the usual approach for checking user input is to include it in the BeforeUpdate Event Handler
    (txtHome_phone_B eforeUpdate(Can cel As Integer)). Notice that has a Cancel parameter.

    If/when Cancel is set to TRUE then the update doesn't proceed - which is different from your logic where it updates to the wrong value before being updated again to the text "Invalid". This goes through your txtHome_phone_A fterUpdate() process twice, of course. Not ideal.

    See if that approach works better for you. If I remember correctly, you won't even need to use SetFocus() when the data fails as it won't move off that Control after a failed update.
    Last edited by NeoPa; 4 hours ago.

    Comment

    Working...