Search code examples
c#winformsrichtextboxtextchanged

RichTextBox is satisfied when finding one match; I want it to keep searching


I have this code, which turns the word or phrase sought red:

private void rtb_TextChanged(object sender, EventArgs e) {
    String textToFind = textBoxWordOrPhraseToFind.Text;
    String richText = rtb.Text;
    if ((textToFind == "") || (richText == "") || (!(richText.Contains(textToFind)))) {
        return;
    }
    tOut.Select(richText.IndexOf(textToFind), textToFind.Length);
    tOut.SelectionColor = Color.Red;
}

...but then it stops - it only reddens the first word or phrase. I want it to give the entire (matching) contents of the RichTextBox the Sammy Hagar treatment.

How do I do so?


Solution

  • RichTextBox doesn't support multiple selections.
    Searching other occurrences of the same text could be done, but you can't keep more than one selection. However the SelectionBackColor property could be changed to simulate the multiple selection behavior.

    The searching could be done in this way

    int pos = 0;
    pos = richText.IndexOf(textToFind, 0);
    while(pos != -1)
    {
        tOut.Select(pos, textToFind.Length); 
        tOut.SelectionBackColor = Color.Red; 
        pos = richText.IndexOf(textToFind, pos + 1);
    }