Tuesday, February 23, 2010

DropDownList Extension method for selecting by value

    /// 
    /// Extension methods for the ASP.NET DropDownList control.
    /// 
    public static class DropDownListExtension
    {
        /// 
        /// Select an item in the DropDownList based on the value
        /// 
        /// The DropDownList to select from
        /// The value to select
        public static void SelectItemByValue(this System.Web.UI.WebControls.DropDownList dropDownList, string valueToSelect)
        {
            try
            {
                dropDownList.SelectedIndex = dropDownList.Items.IndexOf(dropDownList.Items.FindByValue(valueToSelect));
            }
            catch (Exception ex)
            {
                throw new ApplicationException("Unable to set value to " + valueToSelect, ex);
            }
        }

        /// 
        /// Select an item in the DropDownList based on the value after the drop down list has been data bound.
        /// 
        /// The DropDownList to select from
        /// The value to select
        public static void SelectItemByValueAfterDataBound(this System.Web.UI.WebControls.DropDownList dropDownList, string valueToSelect)
        {
            dropDownList.DataBound += delegate(object sender, EventArgs e) { dropDownList.SelectItemByValue(valueToSelect); };
        }
    }