Y.Paulet
Y.Paulet

Reputation: 47

Case insensitive search function in C#

I'd like to create a search function on my DataGridView, behind a button click event. To do that, I used the following source code:

chargerDataGrid();
dg_logiciel.ClearSelection();

string search = txtbox_recherche.Text;
foreach (DataGridViewRow dgvr in dg_logiciel.Rows)
{
    if (!dgvr.Cells[1].Value.ToString().Contains(search))
    {
        dgvr.Visible = false;
    }
}

It's working but I'd like to compare my two strings ignoring case. To do that, I've tried this code:

chargerDataGrid();
dg_logiciel.ClearSelection();

string search = txtbox_recherche.Text;
foreach (DataGridViewRow row in dg_logiciel.Rows)
{
    Regex pattern = new Regex(row.Cells[1].Value.ToString(), RegexOptions.IgnoreCase);
    if (!pattern.IsMatch(search))
    {
        row.Visible = false;
    }
}

Which does not work at all. Am I using badly the Regex class or something?

Upvotes: 1

Views: 420

Answers (2)

Saqib Mustafa Abbasi
Saqib Mustafa Abbasi

Reputation: 158

In your answer what is the meaning of the following parameter and how will it work?

this string str

I mean how will this and static coexist

Upvotes: 0

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51390

Unfortunately, .NET lacks a string.Contains(string, StringComparison) function overload.

But you can easily add such an extension function to your project, as we have a suitable IndexOf overload:

public static class StringExtensions
{
    public static bool Contains(this string str, string value, StringComparison comparison)
    {
        return str.IndexOf(value, comparison) >= 0;
    }
}

Then simply use:

if (!dgvr.Cells[1].Value.ToString().Contains(search, StringComparison.OrdinalIgnoreCase))

or use CurrentCultureIgnoreCase depending of your needs.


As for your regex attempt, it's plainly unnecessary to go to such lengths for that, but your attempt fails because of a combination of the following reasons:

  • You inverted the value you search for and the string you search in. You'd have to build your regex instance with the search string as the pattern.
  • Speaking of which, you should have escaped the search value. If it contains any regex metacharacters the pattern will be invalid. You could have used Regex.Escape for this purpose.

So, the following would have worked, but is not the proper way to do the job:

if (!Regex.IsMatch(row.Cells[1].Value.ToString(), Regex.Escape(search), RegexOptions.IgnoreCase))

Upvotes: 2

Related Questions