Ian
Ian

Reputation: 158

vb.net textbox / richtextbox GetPreferredSize not working

I have a winforms RichTextBox and TextBox (trying both). As I type text, I want the box to get bigger vertically (or smaller vertically) so that all the text is viewable.

I am using the following code in the RichTextBox TextChanged event:

RTB.Height = RTB.GetPreferredSize(New Size(RTB.Width, 0)).Height

This code works in most situations apart from one - when you put in a single word (without spaces) which is larger than the width of the box. Any ideas?

Thanks.

Upvotes: 0

Views: 1182

Answers (2)

Ian
Ian

Reputation: 158

Found the following answer already on Stackoverflow! Just had to search better ...

Private Sub rtb_ContentsResized(ByVal sender As Object, ByVal e As System.Windows.Forms.ContentsResizedEventArgs) Handles txtQuestion.ContentsResized
    Dim h = e.NewRectangle.Height, w = e.NewRectangle.Width
    h = Math.Max(h, sender.Font.Height)
    h = Math.Min(h, Me.ClientSize.Height - 10 - sender.Top)
    h += sender.Height - sender.ClientSize.Height + 1
    sender.Height = h
End Sub

from

Measure String inside RichTextBox Control

Upvotes: 1

rheitzman
rheitzman

Reputation: 2297

Try experimenting with the RTB min and max size properties.

Sounds like setting a max width may address your issue.

Upvotes: 0

Related Questions