Reputation: 145
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
Upvotes: 9
Views: 33805
Reputation: 112782
This will not count any empty lines at 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--;
}
Upvotes: 3
Reputation: 87
If WordWrap
is set to true
and you want the number of lines that are displayed, try:
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;
Upvotes: 1
Reputation: 14432
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();
Upvotes: 19