Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the number of text lines in a TextBox

Tags:

c#

winforms

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.

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.

Thanks

like image 930
user1238798 Avatar asked Dec 04 '22 04:12

user1238798


2 Answers

You can also do this in a shorter way using LinQ. To count the lines and exlcude the last line if it is empty:

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();
like image 139
Abbas Avatar answered Dec 05 '22 17:12

Abbas


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--;
}
like image 28
Olivier Jacot-Descombes Avatar answered Dec 05 '22 16:12

Olivier Jacot-Descombes