locked
How can i keep the lines in the richTextBox to be one under the each other after adding numbers ? RRS feed

  • Question

  • In the form1 constructor:

    string text = File.ReadAllText(@"C:\new 2.txt");
    richTextBox1.Text = text;
    string[] lines = richTextBox1.Lines;
    richTextBox2.Lines = lines;
    AddNumbersToLines(richTextBox1);
    AddNumbersToLines(richTextBox2);
    RichTextboxColorFirstLetter(richTextBox1);


    Then the method AddNumbersToLines:

    private void AddNumbersToLines(RichTextBox Rchtxt)
            {
                string[] lines = Rchtxt.Lines;
                for (int i = 0; i < lines.Length; i++)
                {
                    lines[i] = (i + 1) + " " + lines[i];
                }
                Rchtxt.Lines = lines;
            }


    And RichTextboxColorFirstLetter

    private void RichTextboxColorFirstLetter(RichTextBox Rchtxt)
            {
                for (int i = 0; i < Rchtxt.Lines.Length; i++)
                {
                    int index = Rchtxt.Lines[i].IndexOf(" ");
                    string text = Rchtxt.Lines[i].Substring(0, index);
                    Rchtxt.Select(Rchtxt.GetFirstCharIndexFromLine(i), text.Length);
                    Rchtxt.SelectionColor = Color.Red;
                }
            }

    It's coloring each line numbers.

    But then in places where the numbers start to be double like 10,11,12,13...The text is pushed also so the first lines the text after the numbers is starting not above the other lines.

    For example line 9 and line 10.

    I want that the public in line 9 to be directly above the private in line 10.

    So in line 9 there should be two spaces after the number.

    Tuesday, July 11, 2017 12:59 AM

Answers

  • Either,

    1/ Pad the numbers with leading zeros;

    009 Ninth line

    010 Tenth Line

    Or,

    2. Insert a tab after each number.

             for (int i = 0; i < lines.Length; i++)
             {
                lines[i] = (i + 1) + " \t" + lines[i]; // Add a tab - "\t" - here.
             }

    You can change the tab locations to suit using the RichTextBox's SelectionTabs property.

    • Marked as answer by Chocolade1972 Tuesday, July 11, 2017 2:17 AM
    Tuesday, July 11, 2017 2:08 AM