3

I want to count the number of lines needed for VB multiline textbox to display the whole given string. So that I can increase height of the textbox accordingly during TextChanged event.

Abhay
  • 75
  • 1
  • 1
  • 7
  • 1
    possible duplicate of [How can I show scrollbars on a System.Windows.Forms.TextBox only when the text doesn't fit?](http://stackoverflow.com/questions/73110/how-can-i-show-scrollbars-on-a-system-windows-forms-textbox-only-when-the-text-d) – Hans Passant Nov 15 '12 at 21:00
  • @HansPassant: Helpful but not a duplicate since this question does not ask explicitely for scrollbars or text size. OP would have been satisfied with `TextBox.Lines` if there were actually multiple lines. – Tim Schmelter Nov 15 '12 at 21:20

1 Answers1

4

The TextBox has a Lines property.

int numLines = txt.Lines.Length 

But this only returns 1 during TextChanged event.

Then you have just one line. Lines are separated by Ènvironment.NewLine (VBCrlf). Your text looks like it would have multiple lines but actually it is just wrapped since it's too long for the view.

Try to set the height in TextChanged in this way:

Dim s As SizeF = TextRenderer.MeasureText(txt.Text, txt.Font, txt.ClientRectangle.Size, TextFormatFlags.WordBreak)
txt.Height = CInt(s.Height)
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • Thank you for quick response. But this only returns 1 during TextChanged event. – Abhay Nov 15 '12 at 20:51
  • 1
    @Abhay: Then you have just one line. Lines are separated by `Ènvironment.NewLine` (VBCrlf). Your text looks like it would have multiple lines but actually it is just wrapped since it's too long for the view. – Tim Schmelter Nov 15 '12 at 21:01