Joel in Gö
Joel in Gö

Reputation: 7570

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!

Upvotes: 6

Views: 6028

Answers (2)

Luis
Luis

Reputation: 502

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++;
}

Upvotes: 8

Joel in Gö
Joel in Gö

Reputation: 7570

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.

Upvotes: 1

Related Questions