VB6 Tip: Selecting all text when a Text Box gets the focus
Takeaway: In many applications, especially forms, it is often desirable to have all of a control's text selected when it receives focus. This Visual Basic tip shows you how that is accomplished.
This article originally appeared in the Builder.com Visual Basic e-newsletter. Click here to subscribe automatically.
When the focus moves to a Text Box that contains text, Visual Basic 6's default is to position the caret (editing cursor) at the start of the text. In some applications, it might be more appropriate to have all of the control's text selected when it receives the focus. One advantage to this is that it will delete the existing text if the user starts typing something new. This tip shows you how to implement this behavior.
Related resources
Launch and terminate applications in Visual Basic 6.0
Download:
QuickStart: Visual Basic .NET
Context!
VB
A Text Box has two properties that determine what text, if any, is selected:
- SelStart specifies the character position where the selection starts.
- SelLength specifies the length of the selection, in characters.
You can select all text in a Text Box by setting SelStart to 0 and SelLength to the length of the text. Here's a short procedure that does this:
Sub SelectAllText(tb As TextBox)tb.SelStart = 0
tb.SelLength = Len(tb.Text)
End Sub
Then, for each Text Box that you want to behave this way, call the procedure from the GotFocus event procedure, passing the name of the Text Box as the argument:
Private Sub Text1_GotFocus()SelectAllText Text1
End Sub
This works when the Text Box gets the focus either by tabbing or by a mouse click.
Peter Aitken has been programming with Visual Basic since Version 1.0. He has written numerous books and magazine articles on Visual Basic and other computer and programming topics.
Print/View all Posts Comments on this article
SponsoredWhite Papers, Webcasts, and Downloads
- Live Webcast: Top Ten Challenges with On-Premise Email Management Dell MessageOne
- IBM pureXML for SOA: Unlocking the business value of information IBM
- Microsoft SQL Server 2005: Deployment and Tests in an iSCSI SAN Dell EqualLogic
- Advances in Data Warehouse Performance: I/O Elimination in DB2 IBM
- Demo: Need Disk Space? IBM DB2 9 Compression Demo IBM
Article Categories
- Security
- Security Solutions, IT Locksmith
- Networking and Communications
- E-mail Administration NetNote, Cisco Routers and Switches
- CIO and IT Management
- Project Management, CIO Issues, Strategies that Scale
- Desktops, Laptops & OS
- Windows 2000 Professional, Microsoft Word, Microsoft Excel, Microsoft Access, Windows XP,
- Data Management
- Oracle, SQL Server
- Servers
- Windows NT, Linux NetNote, Windows Server 2003
- Career Development
- Geek Trivia
- Software/Web Development
- Web Development Zone, Visual Basic, .NET

