问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/30617928/count-wrapped-lines-in-a-textbox