Results 1 to 1 of 1

Thread: Count the Total lines in a RichTextBox Accurately

  1. #1

    Thread Starter Kasracer's Avatar
    Join Date
    Jul 2003
    USA, Maryland

    Wink Count the Total lines in a RichTextBox Accurately

    There are a few ways to get the amount of lines from a RichTextBox.

    First method:
    VB Code:
    1. RichTextBox MyRTB = new RichTextBox();
    2. MessageBox.Show(MyRTB.Lines.Length.ToString());

    The problem with the above method is that there is a bug present in .Net 1.0 and 1.1 that causes all Undo and Redo levels to be cleared when calling the lines.Length property.

    So how about a work around?

    VB Code:
    1. RichTextBox MyRTB = new RichTextBox();
    2. MessageBox.Show(MyRTB.GetLineFromCharIndex(Int32.MaxValue).ToString());
    Okay, so we got our work around. Is this accurate? Yes and no. Yes if you don't have WordWrap on. If you do, then this is inaccurate because when lines wrap in your textbox, it's still 1 line but the previous two methods consider 1 line wrapped = 2 lines.

    So if you're making some sort of editor, this can throw things off very quickly.

    What's the accurate way to do this? Why, parsing the RTF of course!

    VB Code:
    1. RichTextBox MyRTB = new RichTextBox();
    2. int count = 0, CharPos = 0;
    3. while (true)
    4. {
    5.     CharPos = MyRTB.Rtf.IndexOf("\\par", CharPos);
    6.     if (CharPos != -1)
    7.     {
    8.         ++count;
    9.         ++CharPos;
    10.     }
    11.     else
    12.     {
    13.         break;
    14.     }
    15. }
    16. MessageBox.Show((count-1).ToString());
    \par is at the beginning of every paragraph in a RichText document so this method simply counts those. Now it'll be accurate even with WordWrap.

    Some things to consider
    There is 1 issue with this method. Apparently, if the RichTextBox is completely empty (as in just created), no \pars exist (actually, it appears all RTF codes are absent at this time) so you'll need to adjust your code when dealing with a RichTextBox that's completely empty.

    I haven't had a chance to check if the Lines.Length bug is fixed in 2.0 (I did submit this to a Microsoft engineer I knew when .Net 1.1 first came out so I would image it is), but this method is still necessary to get an accurate amount of total lines with WordWrap on.

    Also, this method may be made more efficient with some Regular Expressions. I'm just not that good at those
    Last edited by Kasracer; Apr 16th, 2006 at 06:41 AM. - My Personal Website with my blog and portfolio
    Don't Forget to Rate Posts!

    Free Icons: FamFamFam, VBCorner, VBAccelerator
    Useful Links: System.Security.SecureString Managed DPAPI Overview Part 1 Managed DPAPI Overview Part 2 MSDN, MSDN2, Comparing the Timer Classes

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Click Here to Expand Forum to Full Width