Select Text or Value From DropDownList Extension Method

Here is a cool way to select an item from the DropDownList using it's value.

ddlCountries.Items.FindByValue(value).Selected = true;

However I keep forgetting how to do it and end up spending ages searching for it, so here is a very usefull extension method that allows you to select an item from a DropDownList using the text or value of the item without needing to know the index of the item.

using System;
using System.Runtime.Serialization;
using System.Web.UI.WebControls;

namespace Core.ExtensionMethods
{
    public class GenericDropDownListException : Exception, ISerializable
    {
        public GenericDropDownListException(string type, string value) : 
            base(string.Format("Unable to set  \"{0}\" to {1}", type, value)) { }
    }

    public static class DropDownListExt
    {
        public static void SelectValue(this DropDownList bob, string value)
        {
            try
            {
                if (bob.SelectedIndex >= 0)
                    bob.Items[bob.SelectedIndex].Selected = false;
                bob.Items.FindByValue(value).Selected = true;
            }
            catch
            {
                throw new GenericDropDownListException("value", value);
            }
        }

        public static void SelectText(this DropDownList bob, string text)
        {
            try
            {
                if (bob.SelectedIndex >= 0)
                    bob.Items[bob.SelectedIndex].Selected = false;
                bob.Items.FindByText(text).Selected = true;
            }
            catch
            {
                throw new GenericDropDownListException("value", text);
            }
        }
    }
}

Now all you need to do to select an item from the DropDownList is:

ddlCountries.SelectText("UK");
comments powered by Disqus