tags:

views:

417

answers:

2

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

A: 

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.

TLiebe
This would get slow as the number of lines increased.
David Basarab
You're right and I should have put a warning in there but for a reasonable number of lines (less than 100?) it should be fine.
TLiebe
+1  A: 

Find the text to delete in a text range, found here Set the text to empty, and now it is gone form the document.

David Basarab