There was such a question. I have two lines in RichTextBox, and I have to add a number to the first line of the RichTextBox when I click the button. I did by analogy with TextBox.

richTextBox1.Lines[0] += "1"; 

However, the action is not performed. For clarity, I give an example with TextBox.

 textBox1.Text += "1"; 

What is the problem, what is the subtlety here?

    2 answers 2

    The subtlety is that the Lines property each time returns a new array of strings. Your code changes one of the lines in the modified array, which is no longer associated with the source data.

    In theory, this should work:

    1. Save array to local variable
    2. Change the desired string in the array through this variable.
    3. Change the array to the Lines property again.
    • Thanks, I will try. - Svyatoslav

    To add text to richTextBox you need to call AppendText ("text"), but to change a specific line, I don’t know here, I’m interested in it myself.

    It is useful to read MSDN (remarks): Lines on the default read-only, to change you should do this:

     richTextBox1.Lines = new string[] { "строка1", "строка2" };