Visual Basic FAQ

Pure VB: How to Highlight Textbox Text on Gaining Focus
     
Posted:   Thursday December 26, 1996
Updated:   Monday December 26, 2011
     
Applies to:   VB3, VB4-16, VB4-32, VB5, VB6
     
 Prerequisites
None.

This is the code required to have a textbox automatically select its contents on gaining focus. For VB versions not supporting the With statement, place each command on its own line.
 BAS Module Code
None.

 Form Code
Place the following code into the GotFocus sub of the textbox whose contents you want to have highlighted on obtaining focus:

Private Sub Text1_GotFocus()

   With Text1
      .SelStart = 0
      .SelLength = Len(.Text)
   End With

End Sub
 Comments
An object cannot obtain focus during the Form_Load. If you require that the a textbox have focus on the initial displaying of the form, either set that control's Tabstop property to 0, or use an implicit Show statement in the form's Load event:
Sub Form_Load()

  (any form start-up code)
   Me.Show

   Text1.SetFocus

End Sub

 
 

PayPal Link
Make payments with PayPal - it's fast, free and secure!

 
 
 
 

Copyright ©1996-2011 VBnet and Randy Birch. All Rights Reserved.
Terms of Use  |  Your Privacy

 

Hit Counter