Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the format of specified lines in a RichTextBox

I have a winforms RichTextBox containing lots of lines of text (eg 2 MB text files), and would like to programmatically change the formatting of specified lines, eg highlighting them.

How can I address the lines, rather than the characters? Is a RichTextBox even the best control for this sort of thing, or is there another alternative? I have tried the Infragistics UltraFormattedTextEditor, but it was at least a couple of orders of magnitude slower to display text, so no good for my longer files.

Thanks!

like image 591
Joel in Gö Avatar asked Jun 26 '09 12:06

Joel in Gö


2 Answers

To access the lines on textbox controls you use the Lines property

richTextBox.Lines

From there you can iterate through the lines and work with the ones you want to change.

Edit: Agreed, I missed the highlight part (+1 for answering your own question). Including working code:

int lineCounter = 0;
foreach(string line in richTextBox1.Lines)
{
   //add conditional statement if not selecting all the lines
   richTextBox.Select(richTextBox.GetFirstCharIndexFromLine(lineCounter), line.Length);
   richTextBox.SelectionColor = Color.Red;
   lineCounter++;
}
like image 153
Luis Avatar answered Sep 28 '22 17:09

Luis


OK, I'll document the solution I found: using richTextBox.Lines to get the lines as Luis says, then

richTextBox.GetFirstCharIndexFromLine(int line)
richTextBox.Select(int start, int length)

to select the relevant lines, then

richTextBox.SelectionColor...
richTextBox.SelectionBackground...

etc. etc. to format the lines.

like image 43
Joel in Gö Avatar answered Sep 28 '22 18:09

Joel in Gö