Search code examples
c#textboxcursorpasting

Pasting lines of text at the cursor in a textbox


so I'm working on a basic notepad program designed to be helpful toward web designers. I have a list of different blocks of code that can be pasted into the editor, but I'm having trouble pasting them how I want it. Basically, I'd like to be able to click between two lines (or words, whereever) on the text editor, and be able to paste these blocks where the blinking cursor would be.

Here's my current code for when one of the pasting options is selected:

public void getCodeBlock(string selection)
{
    string[] codeBlocks = System.IO.File.ReadAllLines(@"blocks\" + selection + ".txt");
    foreach (string codeBlock in codeBlocks)
    {
        int cursorPosition = richTextBox1.SelectionStart;
        string insertText = codeBlock + Environment.NewLine;
        richTextBox1.Text = richTextBox1.Text.Insert(cursorPosition, insertText);
        cursorPosition = cursorPosition + insertText.Length;
    }
}

However, instead of pasting it at the cursor, it completely jumbles up the lines, and sometimes even pastes it from the last line to the first. I have absolutely no idea what I'm doing wrong, and could really use some help.


Solution

  • It's this line that is causing the problem:

    cursorPosition = cursorPosition + insertText.Length;
    

    Try this instead:

    richTextBox1.SelectionStart = cursorPosition + insertText.Length -1;
    

    The selection position gets reset to 0 when you change the Text property of the richTextBox1. cursorPosition is your local variable which then takes on the new value the next time through the loop.