Keeping Focus in Text field RRS feed

  • Question

  • Hi

    How do I keep the cursor in the text field after validation. Say that the validation failed and I need to keep the cursor in the first field so the user can put in more data to be validated? I have a date field and a description field below it. If user puts in nothing to date field or a string that cannot be converted into a date format (such as 'Garbage') then one of the elseif statements is run in the code below but I want to keep the cursor focus in the date text field AFTER I have pressed 'OK' on the msgbox.

    Also, how do I highlight the Garbage text someone has put in after the validation has run?

    How do you handle message box events as well? Is there a link someone can supply me with for working with message boxes?

    Private Sub txtDateTime_Validate(Cancel As Boolean)

    If IsDate(txtDateTime.Text) Then

    cmdDateFormat.Visible = False

    ElseIf LenB(txtDateTime.Text) = 0 Then

    MsgBox "Enter date/time value before continuing."


    ElseIf Not IsDate(txtDateTime.Text) & LenB(txtDateTime.Text) < 0 Then

    MsgBox ("Use appropriate date format when entering dates.")

    cmdDateFormat.Visible = True

    End If

    End Sub


    Andrew (MCDST)
    Friday, May 1, 2009 2:54 PM


All replies

  • I believe that is what the Cancel parameter is for. Try setting Cancel=true. That should put the focus back into the Textbox.

    As for the msgbox, in .NET it is MessageBox. You don't really handle events from it, but you do get a return value

    dim result as DialogResult = MessageBox.Show(...)

    Hope this helps.
    • Proposed as answer by DeborahKMVP Friday, May 1, 2009 3:13 PM
    Friday, May 1, 2009 2:58 PM
  • I just noticed that! I had forgot all about it. That works now.

    Thanks MVP

    Only require some info on now how to make the text highlighted when focus returns to it. So the user can just start typing new value and does not need to clear old text value.



    Andrew (MCDST)
    Friday, May 1, 2009 3:05 PM
  • Take a look at the .Select* properties. .SelectAll may do what you are looking for.
    Friday, May 1, 2009 3:14 PM
  • Do you mean do this:


    I can only get .SelText

    and it doesn't work, I get error invalid use of property error (.SelText highlighted)


    Andrew (MCDST)
    Friday, May 1, 2009 3:33 PM
  • Is this VB6?

    If so, this is the wrong forum.
    Friday, May 1, 2009 3:37 PM
  • Where's the VB6 forum? I had a look and could only find this forum 'Visual Basic Language'. I take it then that is .net. I've done some .net but learning VB6 just now.

    Andrew (MCDST)
    Monday, May 4, 2009 7:59 AM
  • http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/6a0719fe-14af-47f7-9f51-a8ea2b9c8d6b

    The above link lists several VB 6 resources.

    Good luck!
    Monday, May 4, 2009 3:50 PM