Microsoft KB Archive/153310

= How to Select All Text in a Field When It Gets the Focus =

Article ID: 153310

Article Last Modified on 6/24/2004

-

APPLIES TO


 * Microsoft Visual Basic 4.0 Standard Edition
 * Microsoft Visual Basic 4.0 Professional Edition
 * Microsoft Visual Basic 4.0 Professional Edition
 * Microsoft Visual Basic 4.0 16-bit Enterprise Edition
 * Microsoft Visual Basic 4.0 32-Bit Enterprise Edition

-



This article was previously published under Q153310



SUMMARY
In many cases, it is best to select or highlight the full text of a field when that field gains the focus. This allows the user to simply begin typing to replace the original text with new text or to press TAB to leave text as it is, and move to the next field. This is particularly useful in screens where there are multiple text boxes bound to a Data control for example.



Step by Step Example
 Start a new project in Visual Basic. Form1 is created by default. Place three text boxes on the form named Text1, Text2, and Text3.  Add the following code to the form1 code window: Option Explicit

Sub Form_Load Text1_lostfocus Text2_lostfocus Text3_lostfocus End Sub

Sub SetSelected(ctl As Textbox) ctl.SelStart = 0 ctl.SelLength = Len(ctl.Text) End Sub

Private Sub text1_LostFocus Call SetSelected(text1) End Sub

Private Sub text2_LostFocus Call SetSelected(text2) End Sub

Private Sub text3_LostFocus Call SetSelected(text3) End Sub  On the Run menu, click Start or press F5. You will notice that as you move to each text box, the text is highlighted as opposed to the default behavior of the mouse pointer remaining in front of the first letter in] the text box.

