Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show number of a line in a RichTextBox C#

I am making a simple text and script editor with code highlighting. For that I use a RichTextBox. But I don't know how to make it show the lines' numbers on the left side, like in VS or Notepad++. Is there any solution?

like image 839
fonix232 Avatar asked Apr 02 '10 14:04

fonix232


People also ask

What is RichTextBox control in C#?

In C#, RichTextBox control is a textbox which gives you rich text editing controls and advanced formatting features also includes a loading rich text format (RTF) files. Or in other words, RichTextBox controls allows you to display or edit flow content, including paragraphs, images, tables, etc.

What is RichTextBox in Visual Studio?

In this article The RichTextBox control enables you to display or edit flow content including paragraphs, images, tables, and more. This topic introduces the TextBox class and provides examples of how to use it in both Extensible Application Markup Language (XAML) and C#.


2 Answers

I tried re-using the code from the codeproject articles referenced elsewhere, but every option I looked at, seemed a bit too kludgy.

So I built another RichTextBoxEx that displays line numbers.

The line numbering can be turned on or off. It's fast. It scrolls cleanly. You can select the color of the numbers, the background colors for a gradient, the border thickness, the font, whether to use leading zeros. You can choose to number lines "as displayed" or according to the hard newlines in the RTB.

Examples:

enter image description here

enter image description here

enter image description here

It has limitations: it displays numbers only on the left. You could change that without too much effort if you cared.

The code is designed as C# project. Though it's part of a larger "solution" (an XPath Visualization tool), the custom RichTextBox is packaged as a separable assembly, and is ready to use in your new projects. In Visual Studio, just add a reference to the DLL, and you can drag-and-drop it onto your design surface. You can just discard the other code from the larger solution.

See the code

like image 102
Cheeso Avatar answered Sep 21 '22 22:09

Cheeso


I would store each line in a class which has methods to publish to the richtextbox. In that method, you could prepend the line number based on its position in the class.

For example (very roughly):

class myText
{
    public List<string> Lines;

    public string GetList()
    {
        StringBuilder sb = new StringBuilder();
        int i = 0;
        foreach (string s in Lines)
        {
            sb.AppendFormat("{0}: {1}", i, s).AppendLine();
            i++;
        }
        return sb.ToString();
    }
}
like image 44
JYelton Avatar answered Sep 18 '22 22:09

JYelton