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
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.