Need to have string comparison case insensitive for .net winforms application. It is not a problem when strings are compared in my code, but I need this everywhere. For ex.: there is combobox with items populated from SQL data, where value member is uppercase string, but entity field bound to this combobox as value is allowed to have value (string) lowercase. Same for the rest elements.
Asked
Active
Viewed 1,788 times
0
-
are you doing `str1==str2` sort of stuff somewhere? – TheVillageIdiot Aug 03 '17 at 08:27
-
"not a problem when strings are compared in my code,but I need this everywhere." could you be a little more precise?=! you want to compare strings outside of your code? – Mong Zhu Aug 03 '17 at 08:27
-
There is an example (binding values in combobox), it should be default behavior for string comparison – Dmitry Aug 03 '17 at 08:29
-
@TheVillageIdiot, when the comparison is done in my code, I can use StringComparisonOption.OrdinalIgnoreCase, the problem is that it should be default behavior – Dmitry Aug 03 '17 at 08:35
3 Answers
1
You cannot change the default comparison for strings in .net. .net is a case sensitive language. It has specific methods for comparing strings using different levels of case sensitivity, but (thank goodness) no global setting.

PhillipH
- 6,182
- 1
- 15
- 25
1
You can use this:
string.Equals(a, b, StringComparison.CurrentCultureIgnoreCase);
Or extension method:
public static class StringExtensions
{
public static bool Contains(this string source, string value, StringComparison compareMode)
{
if (string.IsNullOrEmpty(source))
return false;
return source.IndexOf(value, compareMode) >= 0;
}
}
and you can call it like this:
bool result = "This is a try".Contains("TRY",
StringComparison.InvariantCultureIgnoreCase);
Console.WriteLine(result);

alaa_sayegh
- 2,141
- 4
- 21
- 37
-1
Use
if (string1.ToLower().Equals(string2.ToLower()))
{
#something
}
without the code, there is no other advice i can offer you :/
-
1This is not the preferred method to do a case-invariant string comparison because it needlessly allocates lower-cased copies of each string. Instead, follow the advice in [this answer](https://stackoverflow.com/a/13965429/3744182) and do `String.Equals(s1, s2, StringComparison.OrdinalIgnoreCase)`. See [here](https://learn.microsoft.com/en-us/dotnet/standard/base-types/best-practices-strings#specifying_string_comparisons_explicitly) for info; possibly the OP will want to use `StringComparison.CurrentCultureIgnoreCase` for UI purposes. – dbc Aug 03 '17 at 08:55