How to search for a phrase in a RichTextBox and highlight every instance of that phrase with a color you specify

How can one search for a phrase in a RichTextBox and highlight every instance of that phrase with any color desired?

Upvotes: 0

Views: 193

Answers (1)

Replace the string assigned to ValToSearchFor and the color assigned to the RichTextBox's SelectionColor property as desired.

String richText = richTextBox1.Text;
String ValToSearchFor = "duckbilledPlatypus";
int pos = 0;
pos = richText.IndexOf(ValToSearchFor, 0);
while (pos != -1) {
    richTextBox1.Select(pos, ValToSearchFor.Length);
    richTextBox1.SelectionColor = Color.Red;
    pos = richText.IndexOf(ValToSearchFor, pos + 1);
}

Upvotes: 1

Related Questions