Thursday, 21 April 2011

DropDownList.FindByText() case in-sensitive

The default behavior of FindByText() and FindByValue() of ListBox is case sensitive. You have to write your own code to do a case-insensitive search against any list box. One of the UIs which I was working on recently had a country list box where "United Kingdom" had to be selected by default. It was done by binding a country list returned by the middle-tier to the listbox and then doing

CountryListBox.FindByText("United Kingdom").Selected = true


Everything was fine until the middle-tier code started returning a new list where it has "UNITED KINGDOM" in place of "United Kingdom" in the original list. As you know this breaks my code.

This caused me to think about a solution which can do it case-insensitively. And here is what I have come up with.


foreach (ListItem countryListItem in CountryListBox.Items)
{
if (countryListItem.Text.ToLower().Equals("united kingdom"))
{
_ddlCountry.SelectedIndex = -1;
_ddlCountry.Items.FindByText(countryListItem.Text).Selected = true;
}
break;
}


FYI

String.Compare Method (String, String, Boolean) allows to to do case insensitve comparison when you pass the third parameter as true.

Click here to read more about String.Compare()

4 comments: