# VBForums CodeBank > CodeBank - C# >  Count the Total lines in a RichTextBox Accurately

## Kasracer

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

*First method:*

VB Code:
RichTextBox MyRTB = new RichTextBox();
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:
RichTextBox MyRTB = new RichTextBox();
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:
RichTextBox MyRTB = new RichTextBox();
int count = 0, CharPos = 0;
while (true)
{
    CharPos = MyRTB.Rtf.IndexOf("\\par", CharPos);
    if (CharPos != -1)
    {
        ++count;
        ++CharPos;
    }
    else
    {
        break;
    }
}
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  :Stick Out Tongue:

----------

