Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count wrapped lines in a textbox

I have a single line of text in a Text Box and that is wrapped to many lines, how to count no of wrapped lines in Text Box?

like image 825
Shreyas Bhat Avatar asked Dec 06 '25 21:12

Shreyas Bhat


1 Answers

You could use String.Split:

int lineCount = txt.Text.Split(new[] { '\n', 'r' }, StringSplitOptions.None).Length;

If it's a winforms TextBox you can also use the Lines property:

int lineCount = txt.Lines.Length;

So it's VB.NET:

Dim lineCount = txt.Text.Split({vbLf, vbCr}, StringSplitOptions.None).Length

Update: Maybe my understanding was wrong and you want to count the "lines" that the UI-element (like the TextBox) wrapped your single-line text. Then above doesn't work of course.

You could use Text.GetLineFromCharIndex:

Dim lineCount = txt.GetLineFromCharIndex(txt.Text.Length - 1)

I must admit that i didnt know GetLineFromCharIndex before, but it seems to work as expected. I have entered a long single line text and the linecount was 23. After i've reduced the width of the textbox it has changed to 40.

like image 197
Tim Schmelter Avatar answered Dec 08 '25 12:12

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!