Delete a specific line in a .NET RichTextBox

后端 未结 9 1520
后悔当初
后悔当初 2021-01-19 15:08

How can I delete a specific line of text in a RichTextBox ?

相关标签:
9条回答
  • 2021-01-19 15:45

    I don't know if there is an easy way to do it in one step. You can use the .Split function on the .Text property of the rich text box to get an array of lines

    string[] lines = richTextBox1.Text.Split( "\n".ToCharArray() )
    

    and then write something to re-assemble the array into a single text string after removing the line you wanted and copy it back to the .Text property of the rich text box.

    Here's a simple example:

            string[] lines = richTextBox1.Text.Split("\n".ToCharArray() );
    
    
            int lineToDelete = 2;           //O-based line number
    
            string richText = string.Empty;
    
            for ( int x = 0 ; x < lines.GetLength( 0 ) ; x++ )
            {
                if ( x != lineToDelete )
                {
                    richText += lines[ x ];
                    richText += Environment.NewLine;
                }
            }
    
            richTextBox1.Text = richText;
    

    If your rich text box was going to have more than 10 lines or so it would be a good idea to use a StringBuilder instead of a string to compose the new text with.

    0 讨论(0)
  • 2021-01-19 15:45
    int LineToDelete = 50;
    List<string> lines = richTextBox1.Lines.ToList();
    lines.Remove(LineToDelete);
    richTextBox1.Lines = lines.ToArray();
    
    0 讨论(0)
  • 2021-01-19 15:46

    Based on tomanu's solution but without overhead

    int start_index = LogBox.GetFirstCharIndexFromLine(linescount);
    int count = LogBox.GetFirstCharIndexFromLine(linescount + 1) - start_index;
    LogBox.Text = LogBox.Text.Remove(start_index, count);
    

    note that my linescount here is linescount - 2.

    0 讨论(0)
提交回复
热议问题