3

Adding line numbers to a multi-line text box

 3 years ago
source link: https://www.codesd.com/item/adding-line-numbers-to-a-multi-line-text-box.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Adding line numbers to a multi-line text box

advertisements

I have 2 text boxes in my form, one is for the content (mainTextBox), which is on the right, and the other is for the line numbers (linesTextBox), which is on the left. Both boxes are the same height and both are multi-line text boxes.

Every time text changes in mainTextBox I call the method writeLineNumbers(mainTextBox.Lines.Count()) which runs a for loop to populate linesTextBox. It looks like this:

private void mainTextBox_TextChanged(object sender, EventArgs e)
{
    int linecount = mainTextBox.Lines.Count();
    writeLineNumbers(linecount);
}

private void writeLineNumbers(int linecount)
{
    linesTextBox.Text = "";
    int i = 1;
    foreach (var lines in mainTextBox.Lines)
    {
        linesTextBox.AppendText(i + "\n");
        i++;
    }
}

This works, however it is extremely taxing and slow on the system once you get past about 50 lines. I've tried a few other things but I cant seem to find a way to do this.

Ive tried this way but its very glitchy and breaks alot but I think Im on the right track

private void writeLineNumbers(int count)
{
    int lineBoxCount = linesTextBox.Lines.Count();
    int mainBoxCount = count;

    if (lineBoxCount != mainBoxCount && lineBoxCount > mainBoxCount)
    {
        while (lineBoxCount > mainBoxCount)
        {
            linesTextBox.Text = linesTextBox.Text.Remove(linesTextBox.Text.LastIndexOf(Environment.NewLine));
            lineBoxCount--;
        }
    }
    else if (lineBoxCount != mainBoxCount && lineBoxCount < mainBoxCount)
    {
        while (lineBoxCount < mainBoxCount)
        {
            linesTextBox.AppendText(count + "\n");
            lineBoxCount++;
        }
    }
}


It seems you are effectively trying to build the UI you often see in code editors (having line numbers in front).

I would recommend not try to reinvent the wheel, but use an existing control for this. I often use ScintillaNET, which is a .NET wrapper around the common known Scintilla, which is used in Notepad++ for example.

The good news is: you get syntax highlighting for free.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK