How to change the format of specified strings in RichTextBox

I have winforms RichTextBox containing many lines of text (e.g. 2 MB text files) and would like to programmatically change the formatting of the specified lines, for example, select them.

How can I address strings, not characters? Is RichTextBox even the best control for this kind of thing, or is there another alternative? I tried Infragistics UltraFormattedTextEditor, but it was several orders of magnitude slower to display text, so nothing good for my longer files.

Thanks!

+6
string c # controls winforms
source share
2 answers

To access strings in text field controls, you use the Lines property

richTextBox.Lines

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

Edit: I agree, I skipped the highlighted part (+1 to answer 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++; } 
+8
source share

OK, I will document the solution I found: using richTextBox.Lines to get the rows, as Louis says, then

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

to select the appropriate rows, then

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

etc .. etc to format strings.

+1
source share

All Articles