views:

657

answers:

2

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!

+3  A: 

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++;
}
Luis
that gets me the lines; but how can I tell the RichtTextBox to highlight the lines I want, for example? I can only set SelectedText by character number, not by line...?
Joel in Gö
+1  A: 

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.

Joel in Gö