Wednesday, February 17, 2010

DropDownList.SelectItemByValue Extension Method (C#)

This helped me simplify some code today.  Basically it is an extension method for a DropDownList that takes a nullable type value as an argument to find in the list.  If it finds the value it becomes selected, otherwise it selects the first item by default.

In a static class:

public static void SelectItemByValue(this DropDownList dropDownList, Nullable value) where T : struct
    {
        if (value.HasValue)
        {
            ListItem listItem = dropDownList.Items.FindByValue(value.Value.ToString());
            if (listItem != null)
            {
                listItem.Selected = true;
                return;
            }
        }

        if (dropDownList.Items.Count > 0)
        {
            dropDownList.Items[0].Selected = true;
            return;
        }
    }

No comments: