How To Bind Enum To DropDownList

This will set the dropdown text to the enum’s description and the value (int) from the enum.

SeverityType.cs (Enum)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;

namespace com.aep.ehap.bl
{
    /// <summary>
    /// Defines a type of Severity.
    /// </summary>
    public enum SeverityType
    {
        [Description("1 - Injury free event, first aid, non recordable")]
        InjuryFreeEvent = 0,

        [Description("2 - Medical, restricted duty/transfer = <2 days")]
        MedResDutyLessTwoDays = 1,

        [Description("3 - Restricted duty/transfer = <= 10 days")]
        MedResDutyLessTenDays = 2,

        [Description("4 - Restricted duty/transfer = <30 days")]
        MedResDutyLessThirtyDays = 3,

        [Description("5 - Restricted duty/transfer =<60 days")]
        MedResDutyLessSixtyDays = 4,

        [Description("6 - Complete disabling or fatality")]
        DisablingOrFatality = 5

    }
}

Page CodeBehind

          
            // Bind the Dropdown lists

            // Default first value in dropdown
            this.ddlPotentialSeverity.Items.Add(new ListItem() { Text = "Select one...", Value = "-1" });

            // Retrieve list of SeverityType's from enum
            List<SeverityType> SeverityTypes = new List<SeverityType>((SeverityType[])Enum.GetValues(typeof(SeverityType)));

            this.ddlPotentialSeverity.Items.AddRange(
                 (from severityType in SeverityTypes
                  select new ListItem()
                  {
                      Value = severityType.ToString(),
                      Text = Util.GetEnumDescription(severityType)
                  }).ToArray());

Util.cs (GetEnumDescription)


        /// <summary>
        /// Gets the enum description given enum value
        /// </summary>
        /// <param name="value">The value from enum.</param>
        /// <returns></returns>
        public static string GetEnumDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            DescriptionAttribute[] attributes =
                  (DescriptionAttribute[])fi.GetCustomAttributes(
                  typeof(DescriptionAttribute), false);
            return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
        }
Advertisements

One thought on “How To Bind Enum To DropDownList

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