Count wrapped lines in a textbox

这一生的挚爱 提交于 2019-12-24 14:24:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!