Wednesday, 11 April 2012

C# :Count the total number of lines in RichTextBox

All you have to use is RichTextBox.GetLineFromCharIndex method.

int lineNumber = richTextBox1.GetLineFromCharIndex(richTextBox1.TextLength) + 1;
MessageBox.Show(lineNumber.ToString());
This 2 lines of code will give you number of lines in RichTextBox

You will find more detailed explanation here:
GetLineFromCharIndex[^]

Here is complete example of counting total number of lines in RTB

namespace Editor
{
    public partial class Form1 : Form
    {
        private int lineNumber;
        private void richTextBox1_KeyPress(object sender, 
                                            KeyPressEventArgs e)
        {
          lineNumber = richTextBox1.GetLineFromCharIndex(richTextBox1.TextLength) + 1;
          for(int i=1; i<=lineNumber; i++)
               this.lable_line_number.Text = i
               + Environment.NewLine;
         }
    }
}


lineNumber = richTextBox1.GetLineFromCharIndex(richTextBox1.TextLength) + 1;
Whenever you press any key , this line of code will be triggered and counts lines in RTB.

for(int i=1; i<=lineNumber; i++)
    this.lable_line_number.Text = i + Environment.NewLine;
Since you got lines number, just write it into something, say label.

2 comments: