Question

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.

Was it helpful?

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.

OTHER TIPS

I really can't figure out what your code is supposed to do.

I haven't worked much with RichTextBox but, if you want to insert some text at the current position, just do richTextBox1.SelectedText = insertText. (Note that this will replace selected text, if any.)

You can use richTextBox1.SelectionStart and richTextBox1.SelectionLength to alter the current position/selection.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top