Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/269.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取文本框中的文本行数_C#_Winforms - Fatal编程技术网

C# 获取文本框中的文本行数

C# 获取文本框中的文本行数,c#,winforms,C#,Winforms,我试图通过标签显示文本框中的文本行数。但是,问题是,如果最后一行是空的,标签必须显示没有空行的行号 例如,如果它们是5行,最后一行为空,则标签应将行数显示为4 谢谢 private void txt_CurrentVinFilter_EditValueChanged(object sender, EventArgs e) { labelCurrentVinList.Text = string.Format("Current VIN List ({0})", txt_CurrentVinF

我试图通过标签显示文本框中的文本行数。但是,问题是,如果最后一行是空的,标签必须显示没有空行的行号

例如,如果它们是5行,最后一行为空,则标签应将行数显示为4

谢谢

private void txt_CurrentVinFilter_EditValueChanged(object sender, EventArgs e)
{
   labelCurrentVinList.Text = string.Format("Current VIN List ({0})",  txt_CurrentVinFilter.Lines.Length.ToString());                       
}
实际上,上面是代码…必须更改以仅显示C#winforms中的无空行


谢谢

这不会将任何空行计算为结束

int count = tb.Lines.Length;
while (count > 0 && tb.Lines[count - 1] == "") {
    count--;
}
或者,如果要排除仅包含空格的行

int count = tb.Lines.Length;
while (count > 0 && tb.Lines[count - 1].Trim(' ','\t') == "" ) {
    count--;
}

您还可以使用LinQ以更短的方式完成这项工作。要计算行数并删除最后一行(如果为空):

var lines = tb.Lines.Count();
lines -= String.IsNullOrWhiteSpace(tb.Lines.Last()) ? 1 : 0;
要仅统计非空行,请执行以下操作:

var lines = tb.Lines.Where(line => !String.IsNullOrWhiteSpace(line)).Count();

如果
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;

是的,你确实需要问一个问题让人们回答。如果你喜欢答案,就接受它