Home > .Net, .Net 3.0 / 3.5, ASP.Net > Dropdownlist FindByText Problem

Dropdownlist FindByText Problem

Today one of my colleague talked about a simple basic issue with Dropdownlist, the FindByText() method works as case sensitive. Because of this issue, we are getting some exceptions. So I starting looking for alternatives and one way I found it looping the items and compare it. Like the following.

this.ddlItems.SelectedIndex = -1;
foreach (ListItem item in this.ddlItems.Items)
{
    if (item.Text.Equals("Item", StringComparison.CurrentCultureIgnoreCase))
    {
        item.Selected = true;
        break;
    }
}

It is a nice option, I rewrote it as an extension method and works fine. Later I thought of wrting more generic FindByTextMethod() and here the extension method.

/// <summary>
/// Searches the Collection of ListItem with a ListItem.Text property contains the specified text
/// </summary>
/// <param name="items"></param>
/// <param name="text">The text to search for.</param>
/// <param name="stringComparison">One of the System.StringComparison values.</param>
/// <returns>ListItem if the collection contains the text, null otherwise.</returns>
public static ListItem FindByText(this ListItemCollection items,
    string text,
    StringComparison comparisonType)
{
    ListItem result = items.OfType<ListItem>().
        FirstOrDefault(_string => _string.Text.Equals(text, comparisonType));
    return result;
}

And you can use it like this

this.ddlItems.Items.FindByText("Item", StringComparison.CurrentCultureIgnoreCase).Selected = true;

Happy Coding ;)

  1. No comments yet.
  1. No trackbacks yet.