计算文本框中的换行 [英] 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?
推荐答案
您可以使用 String.Split
:
int lineCount = txt.Text.Split(new[] { '\n', 'r' }, StringSplitOptions.None).Length;
如果它是winforms TextBox
,则还可以使用 Lines
属性:
If it's a winforms TextBox
you can also use the Lines
property:
int lineCount = txt.Lines.Length;
所以是VB.NET:
Dim lineCount = txt.Text.Split({vbLf, vbCr}, StringSplitOptions.None).Length
更新:也许我的理解是错误的,您想计算UI元素(如 TextBox
)包裹单行文本的行数".那么以上当然是行不通的.
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)
我必须承认我之前不知道 GetLineFromCharIndex
,但是它似乎可以正常工作.我输入了很长的单行文本,行数为23.减小文本框的宽度后,其宽度已更改为40.
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.
这篇关于计算文本框中的换行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!