WoodChuckChuck
WoodChuckChuck

Reputation: 69

vb.net Autosize Multiline Textbox height with wordwrap

I'm trying to make a fixed width textbox in a windows forms app in visual studio 2013 that will begin as a single line in height and expands as the user types and either the text wraps (wordwrap) or when the user pushes enter to create a new line. Ideally i would like to set a max height at which point a vertical scroll bar would be added. Also, the textbox should shrink when the user deletes content as well.

Would also much prefer to be able to use a rich text box however I would settle for a regular text box.

Please tell me it doesn't require some crazy workaround to do what should be relatively easy.

Thanks in advance!!

Upvotes: 2

Views: 5830

Answers (3)

Meir Bookatz
Meir Bookatz

Reputation: 31

I used

txtBox.Height = txtBox.Font.Height * (txtBox.Lines.Count + 1)

Upvotes: 1

VBobCat
VBobCat

Reputation: 2732

This worked for me:

Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) _
    Handles TextBox1.TextChanged
    TextBox1.Height = 
        TextRenderer.MeasureText(
            TextBox1.Text,
            TextBox1.Font,
            New Size(TextBox1.ClientSize.Width, 1000),
            TextFormatFlags.WordBreak
        ).Height
End Sub

Upvotes: 3

David Wilson
David Wilson

Reputation: 4439

If you want to use a rich textbox then try adding this to your form's class - remembering to rename all the bits that say"RichTextBox1" to the name of your richtextbox name

Private Sub richTextBox1_ContentsResized(sender As Object, e As contentsResizedEventArgs) Handles RichTextBox1.ContentsResized
    RichTextBox1.Height = e.NewRectangle.Height + 12
End Sub

The only downside of this is that whatever size you initially chose for your richtextbox, it will be ignored as the above event fires when the form loads

Upvotes: 0

Related Questions