Click here to Skip to main content
15,921,174 members
Articles / Programming Languages / Visual Basic
Article

How To Make an AutoSizeTextBox

Rate me:
Please Sign up or sign in to vote.
1.60/5 (5 votes)
13 Oct 2008CPOL 28.8K   553   19   4
How to size a TextBox to fit its contents
AutoSizeTextBoxDemo

Introduction

This small Windows application makes any TextBox fit its contents like Google toolbar's Search TextBox in Internet Explorer.

Background 

This application is very easy to understand and needs no particular background.

Using the Code

We use the TextChanged event of the TextBox to resize it. First of all, we need to get the Graphics object from TextBox using the CreateGraphics() method inherited from the Control class.

Then, use the MeasureString method that has several overloads. The simplest of them gets two parameters, a String and a Font object to determine the width of a given string. The return value for this method is a SizeF structure containing Width and Height. We also use a padding value to prevent text from sticking to the right border of TextBox.

VB.NET
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, 
	ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    Dim g = TextBox1.CreateGraphics()
    Dim s As SizeF = g.MeasureString(TextBox1.Text, TextBox1.Font)
    TextBox1.Width = s.Width + NumericUpDownPadding.Value      
End Sub	

History

  • 13th October, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Iran (Islamic Republic of) Iran (Islamic Republic of)
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionUser Control - VB.Net Version Pin
SumitSaha20-Nov-15 15:17
SumitSaha20-Nov-15 15:17 
GeneralUserControl Pin
Günther M. FOIDL14-Oct-08 9:07
Günther M. FOIDL14-Oct-08 9:07 
GeneralRe: UserControl Pin
Jon_Boy21-Oct-08 1:44
Jon_Boy21-Oct-08 1:44 
GeneralMemory leak Pin
JoseMenendez14-Oct-08 7:46
JoseMenendez14-Oct-08 7:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.