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.