using Enums as data source for a drop down list box in asp.net

We can discuss the merits of using enums as data sources at a different time. But I needed to use an enum as datasource and wanted to have a space in one of the enum values. The article by Luke explains how we can go about it. I updated code just a bit to stream line adding the enum as datasource to drop down list control.

 #region Enum Description

 

        /// <summary>

        /// Gets the enum list.

        /// </summary>

        /// <typeparam name=”T”></typeparam>

        /// <returns></returns>

        public static List<string> GetEnumList<T>()

        {

            List<string> enumValues = new List<string>();

            foreach (T enumVal in EnumToList<T>())

            {

                enumValues.Add(GetEnumDescription(enumVal));

            }

            return enumValues;

        }

 

        /// <summary>

        /// Enums to list.

        /// </summary>

        /// <typeparam name=”T”></typeparam>

        /// <returns></returns>

        public static List<T> EnumToList<T>()

        {

            Type enumType = typeof(T);

 

            // Can’t use generic type constraints on value types,

            // so have to do check like this

            if (enumType.BaseType != typeof(Enum))

                throw new ArgumentException(“T must be of type System.Enum”);

 

            Array enumValArray = Enum.GetValues(enumType);

            List<T> enumValList = new List<T>(enumValArray.Length);

 

            foreach (int val in enumValArray)

            {

                enumValList.Add((T)Enum.Parse(enumType, val.ToString()));

            }

 

            return enumValList;

        }

 

 

        /// <summary>

        /// Gets the enum description.

        /// </summary>

        /// <typeparam name=”T”></typeparam>

        /// <param name=”value”>The value.</param>

        /// <returns></returns>

        public static string GetEnumDescription<T>(T value)

        {

 

            Type enumType = typeof(T);

 

            // Can’t use generic type constraints on value types,

            // so have to do check like this

            if (enumType.BaseType != typeof(Enum))

                throw new ArgumentException(“T must be of type System.Enum”);

 

            FieldInfo fi = value.GetType().GetField(value.ToString());

 

            DescriptionAttribute[] attributes =

                (DescriptionAttribute[])fi.GetCustomAttributes(

                    typeof(DescriptionAttribute),

                    false);

 

            if (attributes != null && attributes.Length > 0)

                return attributes[0].Description;

            else

                return value.ToString();

        }

 

        /// <summary>

        /// Gets the eum from description.

        /// </summary>

        /// <typeparam name=”T”></typeparam>

        /// <param name=”value”>The value.</param>

        /// <returns></returns>

        public static T GetEumFromDescription<T>(string value)

        {

            Type enumType = typeof(T);

            if (enumType.BaseType != typeof(Enum))

                throw new ArgumentException(“T must be of type System.Enum”);

 

            T returnValue = default(T);

            foreach (T enumVal in EnumToList<T>())

            {

                if (GetEnumDescription(enumVal) == value)

                {

                    returnValue = enumVal;

                    break;

                }

            }

            return returnValue;

        }

        #endregion

Sample Enum

using System.ComponentModel;

namespace TestEnumNameSpace

{

   public enum AgentDrugResult

    {

        Intermediate,

        [Description(“Not Done”)]

        NotDone,

        Resistant,

        Susceptible,

        Unknown,

    }

}

Call to attach the sample enum as datasource

 ddl.DataSource = GetEnumList<AgentDrugResult>();

Advertisements

About Shashi Kuppa

I have 14 years of Information System experience. My background ranges from software architecture, analysis, design and development to team leadership and project management. My primary strengths include .Net system architecture, object oriented development using C#, web development using Asp.net and SQL server development, reporting and integration. I am an excellent team player, good communicator and have a proven track record for goal-oriented project leadership and management
This entry was posted in Development and tagged . Bookmark the permalink.

One Response to using Enums as data source for a drop down list box in asp.net

  1. Sriram says:

    Good job Shashi.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s