C# – displaying line number in rich text box c#

cline-numbersmultilinetextbox

I have a Multiline richtextbox control into which i want to integrate the feature of adding a line number. i have considered many approaches

  1. Add a label and updating the line numbers as the line count changes
  2. Add a picturebox along with to draw string on it.
  3. Add another textbox along with and show line numbers on it
  4. Add listbox along and display line numbers in it.

I got two doubts.

  1. The richtextbox which i'm using is a custom made control and derieves from RichTextBox class. How can i add multiple controls to it.
  2. What is the best approach to show line numbers for the multiline text in c#

Best Answer

My own example. All is fine, but wordwrap must be disabled :(

    int maxLC = 1; //maxLineCount - should be public
    private void rTB_KeyUp(object sender, KeyEventArgs e)
    {
        int linecount = rTB.GetLineFromCharIndex( rTB.TextLength ) + 1;
        if (linecount != maxLC)
        {
            tB_line.Clear();
            for (int i = 1; i < linecount+1; i++)
            {
                tB_line.AppendText(Convert.ToString(i) + "\n");
            }
            maxLC = linecount;
        }
    }

where rTB is my richtextbox and tB is textBox next to rTB

J.T. jr