I've the following code to search and high light a string in a rich text box but it seems like it works on some and not on some. Suppose my Rich Text Box Text string is "CUST.DATA.OBJ-1681 sometext and sometext and sometext" and if I search on "CUST.DATA.OBJ" then it works but if search on "CUST.DATA.OBJ-1681" then it's not working. I can't figure it out. Could someone tell me what I'm doing wrong. Below is my code

    static void HighlightPhrase(RichTextBox box, string phrase, Color color)
        int pos = box.SelectionStart;
        string s = box.Text;
        for (int ix = 0; ; )
            int jx = s.IndexOf(phrase, ix, StringComparison.OrdinalIgnoreCase);
            if (jx < 0) break;
            box.SelectionStart = jx;
            box.SelectionLength = phrase.Length;
            box.SelectionColor = color;
            ix = jx + 1;
        box.SelectionStart = pos;
        box.SelectionLength = 0;
5 Years
Discussion Span
Last Post by thines01

Would it be easer to see if the rtb contains the substring (the easy way), first?

if (richTextBox1.Text.Contains(tbSearch.Text))
   richTextBox1.SelectionColor = color;
   richTextBox1.SelectionStart = richTextBox1.Text.IndexOf(tbSearch.Text, StringComparison.CurrentCultureIgnoreCase);
   richTextBox1.SelectionLength = tbSearch.Text.Length;
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.