C# - Numbering lines in richTextBox Windows Forms

81 views Asked by At

got a problem that can't deal with. I'm trying to number all lines in richTextBox, program does work, but it crashes when I click on my numbering button. Can anyone explain me please why?

Code:

public string temp = null;
private void button1_Click(object sender, EventArgs e)
{
    int i;
    for (i=1;i<richTextBox1.Lines.Length+1;i++)
    {
         temp = richTextBox1.Lines[i];
         richTextBox1.Lines[i] = i + ": " + temp;
    }
}
1

There are 1 answers

0
Fredrik Mörk On BEST ANSWER

The array exposed by the Lines property is zero based. You will want to change your for loop declaration to this:

for (i=0;i<richTextBox1.Lines.Length;i++)

As your code looks now you will try to access elements in the array that are out of bounds (as well as missing the first line).