Friday, 7 November 2014

C# WinForms and WPF - Getting an Accurate Line Count for a Multline Textbox


You may have used the TextBox.LineCount Property for a standard Textbox control, but you'll quickly notice that if lines overflow onto the next line you'll have an extra line added to your line count. Really, you would like to count every physical line (Which ends in a physical return. I.e. \r\n)

Here is a code snippet that I use, it also ignores empty lines...

Code Snippet
  1. string[] lines = System.Text.RegularExpressions.Regex.Split(MULTILINETEXTBOX.Text.Trim(), "\r\n");
  2. int lineCount = lines.Length;
End of Code Snippet

No comments: