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
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();
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--;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With