C# 获取 TextBox 中的文本行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9606818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the number of text lines in a TextBox
提问by user1238798
I am trying to display the number of text lines in a textbox through the label.But, the thing is if the last line is empty, the label has to display the line numbers with out that empty line.
我试图通过标签显示文本框中的文本行数。但是,问题是如果最后一行是空的,标签必须显示没有空行的行号。
For example if they are 5 line with the last line as empty, then the label should display the number of lines as 4.
例如,如果它们是 5 行,最后一行为空,则标签应显示行数为 4。
Thanks..
谢谢..
private void txt_CurrentVinFilter_EditValueChanged(object sender, EventArgs e)
{
labelCurrentVinList.Text = string.Format("Current VIN List ({0})", txt_CurrentVinFilter.Lines.Length.ToString());
}
Actually, above is the code...have to change to display only the no-empty lines in C# winforms.
实际上,上面是代码...必须更改以仅显示 C# winforms 中的非空行。
Thanks
谢谢
回答by Olivier Jacot-Descombes
This will not count any empty lines as the end
这不会将任何空行计为结尾
int count = tb.Lines.Length;
while (count > 0 && tb.Lines[count - 1] == "") {
count--;
}
Or, if you want to exclude also lines containing only whitespaces
或者,如果您还想排除仅包含空格的行
int count = tb.Lines.Length;
while (count > 0 && tb.Lines[count - 1].Trim(' ','\t') == "" ) {
count--;
}
回答by Abbas
You can also do this in a shorter way using LinQ. To count the lines and exlcude the last line if it is empty:
您还可以使用 LinQ 以更短的方式执行此操作。要计算行数并排除最后一行(如果为空):
var lines = tb.Lines.Count();
lines -= String.IsNullOrWhiteSpace(tb.Lines.Last()) ? 1 : 0;
And to count only non-empty lines:
并且只计算非空行:
var lines = tb.Lines.Where(line => !String.IsNullOrWhiteSpace(line)).Count();
回答by dCake
If WordWrapis set to trueand you want the number of lines that are displayed, try:
如果WordWrap设置为true并且您想要显示的行数,请尝试:
int count = textBox1.GetLineFromCharIndex(int.MaxValue) + 1;
// Now count is the number of lines that are displayed, if the textBox is empty count will be 1
// And to get the line number without the empty lines:
if (textBox1.Lines.Length == 0)
--count;
foreach (string line in textBox1.Lines)
if (line == "")
--count;

