Auto-adjust height of richtextbox (or textbox) based on length of string?

P

papalarge

Hey all...

I've been using the following to calculate the height the textbox
needs to be in order to grow it vertically to its necessary size.

textbox1.Height = Me.CreateGraphics().MeasureString(textbox1.Text,
textbox1.Font, textbox1.Width).Height

However it's not appearing to work that well, especially when I'm
using a RichTextbox control, and adjusting it (or checking it) on each
KeyDown event.

Private Sub richtextbox1_KeyPress(ByVal sender As Object, ByVal e As
System.Windows.Forms.KeyPressEventArgs) Handles RichTextBox1.KeyPress
' ADJUSTS HEIGHT OF LABEL BASED ON AMOUNT OF TEXT
RichTextBox1.Height =
Me.CreateGraphics().MeasureString(RichTextBox1.Text,
RichTextBox1.Font, RichTextBox1.Width).Height
End Sub

Any other methods of determining this? In the end, I'd like a
richtextbox control that grows vertically (only) as the text wraps to
a second line (and only grows at that point, no sooner)

Thanks...
 
P

papalarge

Wow... found the answer, was easier than I thought. It takes into
account at least bold, underline text. Not sure about tables, etc.
though.

Private Sub RichTextBox1_ContentsResized(ByVal sender As Object, ByVal
e As System.Windows.Forms.ContentsResizedEventArgs) Handles
RichTextBox1.ContentsResized
' THE "10" IS FOR THE SIZE DIFFERENCE BETWEEN THE HEIGHT OF YOUR FONT
AND THE PADDING YOU'D LIKE TO GIVE IT
If RichTextBox1.Height <> e.NewRectangle.Height + 10 Then
RichTextBox1.Height = e.NewRectangle.Height + 10
End If
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top