Make search terms on richtextbox case insensitive c#

157 Views Asked by At

I have a richtextbox that I've added a search and highlight function to but it will only search for exactly what the user types. I know this is because of the MatchCase property but none of the other options seem to do the job. Here is my code:

private void btnSourceSearch_Click(object sender, EventArgs e)
{
     int start = 0;
     int end = richTextBox1.Text.LastIndexOf(textBox1.Text);

     richTextBox1.SelectAll();
     richTextBox1.SelectionBackColor = Color.White;

     while(start < end)
     {
          richTextBox1.Find(textBox1.Text, start, richTextBox1.TextLength, RichTextBoxFinds.MatchCase);

          richTextBox1.SelectionBackColor = Color.Yellow;

          start = richTextBox1.Text.IndexOf(textBox1.Text, start) + 1;
     }
}

Any help would be greatly appreciated. It's probably simple but I've been looking at code for a good few hours over the last week and it's beginning to look a lot like the Matrix!

Thanks

3

There are 3 best solutions below

1
On BEST ANSWER

I don’t know if you are familiar with regular expressions, but they are useful in this situation. I am not that familiar with them but felt I would give this a shot using them. Without them, using your approach, you will have to check somehow all the case possibilities. That’s where regular expressions are your friend. Below is the code that creates a regular expression from the text in the text box. Then I use that expression to get the Matches in the text in the RichTexBox to highlight. Hope this helps.

private void button1_Click(object sender, EventArgs e) {
  richTextBox1.SelectAll();
  richTextBox1.SelectionBackColor = Color.White;
  if (textBox1.Text.Length < 1)
    return;
  string pattern = @"\b" + textBox1.Text.Trim() + @"\b";
  Regex findString = new Regex(pattern, RegexOptions.IgnoreCase);
  foreach (Match m in findString.Matches(richTextBox1.Text)) {
    richTextBox1.Select(m.Index, m.Length);
    richTextBox1.SelectionBackColor = Color.Yellow;
  }
}
0
On

You could do your search by adding Text.ToUpper() method. Add .ToUpper() method in your richTextBox1.Text and search text both.

0
On

As mentioned use the ToUpper() or ToLower() method for all texts that you operate with. But I also wonder if you shouldn't add the event to search while typing instead of waiting for full string. That would be more intuitive and easier to troubleshoot at all.