Delete a specific line in a .NET RichTextBox

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

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

9条回答
  •  -上瘾入骨i
    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.

提交回复
热议问题