Vb.net – Count number of lines in VB multiline textbox

countlinestextboxvb.net

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.

Best Answer

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)