Fanto
Fanto

Reputation: 137

case insensitivity on textbox not working

I have a textbox used to make research by keywords in a datatable. When the table displays all the searched words are highlighted in yellow. The problem is that if I search "hello" and in the datatabase it is written "Hello" or "HELLO" the word won't be highlighted, I used toLower() but it's not changing anything, can someone give me ideas?

string word = tbSearch.Text.ToLower().Replace("'", " ");

e.Row.Cells[2].Text = ((DataRowView)e.Row.DataItem).Row[2]
    .ToString()
    .ToLower()
    .Replace(tbSearch.Text, "<b class='highlighted'>" + tbSearch.Text + "</b>");

I tried that code it works if I make the research in minuscule, but if in the research I write "HELLO" it won't work. What I want is to recognize the keyword and highlight it regardless of case.

Upvotes: 0

Views: 211

Answers (2)

Manfred Radlwimmer
Manfred Radlwimmer

Reputation: 13394

The current approach changes the casing of the input string. I'd recommend a different approach:

public static string Highlight(string text, string highlight, string prepend, string append)
{
    StringBuilder result = new StringBuilder();
    int position = 0;
    int previousPosition = 0;

    while (position >= 0)
    {
        position = text.IndexOf(highlight, position, 
            StringComparison.InvariantCultureIgnoreCase);

        if (position >= 0)
        {
            result.Append(text.Substring(previousPosition, position - previousPosition));
            result.Append(prepend);
            result.Append(text.Substring(position, highlight.Length));
            result.Append(prepend);

            previousPosition = position + highlight.Length;
            position++;
        }
        else
        {
            result.Append(text.Substring(previousPosition));
        }
    }
    return result.ToString();
}

With this method, the result of

string x = "This test Test TEST should be highTESTjk lighted TeS";
string y = Highlight(x, "test", "<b>", "</b>");

would turn

This test Test TEST should be highTESTjk lighted TeS

into

This test Test TEST should be highTESTjk lighted TeS

instead of

this test test test should be hightestjk lighted tes

Upvotes: 1

Luaan
Luaan

Reputation: 63742

The problem is that string.Replace is case sensitive. So you'll need a way to replace that doesn't care about the case. Unfortunately, there's no way to make string.Replace case insensitive. Fortunately, we have regex:

var text = "This is my hello";
var searchText = "MY";

var result = 
  Regex.Replace
  (
    text, 
    Regex.Escape(searchText), 
    i => string.Format("<b class=\"highlighted\">{0}</b>", i.Value),
    RegexOptions.IgnoreCase
  );

Console.WriteLine(result); // This is <b class="highlighted">my</b> hello

Since you're probably going to use the same pattern many times over, you might want to keep a cached compiled instance of the regex, but that's up to you.

Upvotes: 2

Related Questions