Click here to Skip to main content
Licence CPOL
First Posted 13 Oct 2008
Views 12,954
Downloads 234
Bookmarked 19 times

How To Make an AutoSizeTextBox

By | 13 Oct 2008 | Article
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.

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)

About the Author

saratan60

Web Developer

Iran (Islamic Republic Of) Iran (Islamic Republic Of)

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralUserControl PinmemberGünther M. FOIDL9:07 14 Oct '08  
GeneralRe: UserControl Pinmemberkissdznuts1:44 21 Oct '08  
GeneralMemory leak PinmemberJose M. Menendez Poó7:46 14 Oct '08  

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

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120517.1 | Last Updated 14 Oct 2008
Article Copyright 2008 by saratan60
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid