Xfrogman43
Xfrogman43

Reputation: 3

How to make a textbox case insensitive

Yes, I realize that there are many things on this, but they aren't working for me.

        if (textBox1 != null)
        {
            string text = textBox1.Text;
            foreach (string s in apple)
            {
                if (s.Contains(text))
                {
                    listBox1.Items.Add(s);
                }
            }
        }

In the listbox, I have: "Bob" and "Joe". The textbox searches for names but if I put in "joe", then it doesn't show joe's name, however, if I put "Joe", it shows the name.

Upvotes: 0

Views: 5033

Answers (4)

Rohit Vats
Rohit Vats

Reputation: 81253

Use String.IndexOf which gives you overload for StringComparison instead -

if(s.IndexOf(text, StringComparison.InvariantCultureIgnoreCase) != -1)
{

}

Add this as an extension method to your project which i feel should already be there -

public static class StringExtensions
{
    public static bool Contains(this string value, string valueToCheck, 
                                StringComparison comparisonType)
    {
        return value.IndexOf(valueToCheck, comparisonType) != -1;
    }
}

Now you can use it like this from your method -

if (s.Contains(text, StringComparison.InvariantCultureIgnoreCase))

Upvotes: 0

Douglas
Douglas

Reputation: 54887

Unfortunately, the String.Contains method does not have an overload that takes a StringComparison argument to allow case-insensitive comparisons. However, you can use the String.IndexOf method instead.

if (s.IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0)

Upvotes: 1

Giannis Paraskevopoulos
Giannis Paraskevopoulos

Reputation: 18411

Try ToLower() to all:

if (s.ToLower().Contains(text.ToLower()))

Upvotes: 3

Tinwor
Tinwor

Reputation: 7973

You can use the string method ToLower() if you want all letter lower or ToUpper() if you want all letter Upper

Ex:

if(txt!=null)
{
    string text=txt.Text.ToLower();
    foreach(string s in apple)
       if(s.ToLOwer().Equals("YourString")
           lst.Items.Add(s);
}

Upvotes: 2

Related Questions