How do i Duplicate a line in Richtextbox C#

78 views Asked by At

test 123

after click "duplicate":

test 123 test 123

No matter where the cursor is copy the entire line to the next line

i tried:

int selectionStart = richTextBox1.SelectionStart;
int lineStart = richTextBox1.GetFirstCharIndexOfCurrentLine();
int lineEnd = richTextBox1.GetFirstCharIndexFromLine(richTextBox1.GetLineFromCharIndex(selectionStart) + 1);

if (lineEnd == -1)
{
    // Last line in the RichTextBox
    lineEnd = richTextBox1.Text.Length;
}

string selectedLine = richTextBox1.Text.Substring(lineStart, lineEnd - lineStart);

// Insert the duplicated line after the current line
richTextBox1.Text = richTextBox1.Text.Insert(lineEnd, Environment.NewLine + selectedLine);

// Move the cursor to the end of the duplicated line
richTextBox1.SelectionStart = lineEnd + Environment.NewLine.Length;
            richTextBox1.ScrollToCaret();

thanks, but i solved my problem

    int currentLine = EditingArea.GetLineFromCharIndex(EditingArea.SelectionStart);
    int lineCharIndex = EditingArea.SelectionStart;
    string[] lines = EditingArea.Lines;
    string[] newLines = new string[lines.Length + 1];
    for (int i = 0; i < newLines.Length; i++)
    {
        if (i == currentLine) lineCharIndex += lines[i].Length + 1;
        if (i > currentLine)
        {
            newLines[i] = lines[i - 1];
            continue;
        }
        newLines[i] = lines[i];
    }
    EditingArea.Lines = newLines;
    EditingArea.SelectionStart = lineCharIndex;
1

There are 1 answers

2
Pratap Gowda On
int selectionStart = richTextBox1.SelectionStart;
int lineStart = richTextBox1.GetFirstCharIndexOfCurrentLine();
int lineEnd = richTextBox1.GetFirstCharIndexFromLine(richTextBox1.GetLineFromCharIndex(selectionStart) + 1);
if (lineEnd == -1)
{
    lineEnd = richTextBox1.Text.Length;
}
string selectedLine = richTextBox1.Text.Substring(lineStart, lineEnd - lineStart);
richTextBox1.Text = richTextBox1.Text.Insert(lineEnd, Environment.NewLine + selectedLine);
richTextBox1.SelectionStart = lineStart;
richTextBox1.SelectionLength = selectedLine.Length + Environment.NewLine.Length;
richTextBox1.ScrollToCaret();