65.9K
CodeProject is changing. Read more.
Home

How To Make an AutoSizeTextBox

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.60/5 (5 votes)

Oct 14, 2008

CPOL
viewsIcon

29008

downloadIcon

553

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