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!
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++;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With