Auto Adjusting Text Box

ss7thirty

Well-known member
Joined
Jun 14, 2005
Messages
455
Location
New Jersey, US
Programming Experience
5-10
I need to create a text box that adjusts to the font as it is typed. I have some code but it only works assuming that all letters are the same size.

I need to figure out how to find the size of a specific character or another way to go about expanding a text box to make all the font typed visible until the text box reaches a certain size.

Private Sub t_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles t.TextChanged


Dim sing AsSingle = t.Font.SizeInPoints
Dim accum AsInteger = 0


For Each c As Char In t.Text.ToCharArray
accum += sing

Next
If accum > t.Width Then

t.Width = accum + 5

ElseIf accum < 50 Then

t.Width = 50

ElseIf accum < t.Width Then

t.Width = accum + 5

EndIf
End Sub


 
It's a lot easier than you think:
VB.NET:
Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
    Me.TextBox1.Size = Me.TextBox1.PreferredSize

    Dim selStart As Integer = Me.TextBox1.SelectionStart

    Me.TextBox1.SelectionStart = 0
    Me.TextBox1.SelectionStart = selStart
End Sub
The last three lines may look odd but they are required. Comment them out and see what happens. If the font used in the TextBox can change then you'd want to execute this code on the FontChanged event too. In that case you have two choices. You can remove the code to its own method and call that method from both event handlers, or you can use the same method to handle both events because they have the same signature.

Finally, you may want to set the MaximumSize and MinimumSize properties to prevent the control getting too big or too small and not looking right.

Slight adjustment:
VB.NET:
Me.TextBox1.Width = Me.TextBox1.PreferredSize.Width
 
Thanks

Thank you very much that worked a lot better than I was doing it before. The way I had it was just a bit off. Sometimes things are a lot easier than they seem and to think I spent an hour of my time trying to figure something that basic out using graphics objects, font objects, etc.

thanks much,

Steve-0
 
Back
Top