IT researcher
IT researcher

Reputation: 3304

Fit the text inside a TextBox in VB.net windows forms

In one of my application i require to place the text inside a textbox and textbox width and height must change according to the length of text. So i am using

TextSize = gr.MeasureString(textcontent, TextFont)

where textcontent is content of text and TextFont is type of font.(refer this link)

But if text contains large number of character say it require about 2 lines inside a form(if the text will not fit in single line) then i need to set height also. So I want the text to be fit properly inside the textbox for any given text. Also if there are is case of multiple lines(for large text) then there should be not be extra space at the end of first line and between second line. So how it can be done?

Upvotes: 2

Views: 2498

Answers (2)

Sarvesh Mishra
Sarvesh Mishra

Reputation: 2072

Do something like this...

  1. Decide maximum width (Mx) of textbox according to size of form or as you wish.
  2. Calculate length L required for a string as you are doing.. TextSize = gr.MeasureString(textcontent, TextFont)
  3. If L is less than or equals to Mx then change the width of textbox to L.
  4. If L is Greater than Mx then Height factor (Hf) = L/Mx. Set txtBox1.Multiline = true and change txtBox1 height to txtBox1.Height * Hf and set txtBox1 width = Mx

Upvotes: 1

chris_techno25
chris_techno25

Reputation: 2477

It's going to be harder if you use a regular TextBox control since the properties are limited. So I've taken the liberty to suggest to use the RichTextBox control instead since it's still a TextBox but with more features... So try to put a RichTextBox control onto your form and add this code...

Private Sub RichTextBox1_ContentsResized(sender As Object, e As System.Windows.Forms.ContentsResizedEventArgs) Handles RichTextBox1.ContentsResized
    RichTextBox1.Height = e.NewRectangle.Height + 12
End Sub

Upvotes: 2

Related Questions