Here’s a nice trick I recently found.

Let’s say you have an enum and want to render the enum choices to a dropdown list. But the enum values don’t permit spaces, so they won’t render in an easy-to-read fashion.

This tip creates an extension for enums that allows for a string value decorator on each enum choice. The decorator permits a friendly name to be specified. The extension adds a method to all enums that make it easy to pull the friendly name value.

Start by setting up an enum class like this:

namespace CommerceBuilder.Products
{
    public enum DigitalAssetType
    {
        NotSpecified= 0,
        
        UserManual = 10,

        MSDS = 20,

        TipsTricks = 30,

        Hazards = 40
    }
}

Now create an Extensions class to use in your project.

using System;
using System.ComponentModel;
using System.Reflection;

namespace AbleMods
{
    public static class Extensions
    {
        public static string GetDescription(this Enum value)
        {
            Type type = value.GetType();
            string name = Enum.GetName(type, value);
            if (name != null)
            {
                FieldInfo field = type.GetField(name);
                if (field != null)
                {
                    DescriptionAttribute attr =
                        Attribute.GetCustomAttribute(field,
                            typeof(DescriptionAttribute)) as DescriptionAttribute;
                    if (attr != null)
                    {
                        return attr.Description;
                    }
                }
            }
            return null;
        }
    }
}

With the extension built, we can now add Description[] decorators to each enum value as show here:

    public enum DigitalAssetType
    {

        [Description("Not Specified")]
        NotSpecified = 0,

        [Description("User Manual")]
        UserManual = 10,

        [Description("Material Safety")]
        MSDS = 20,

        [Description("Tips & Tricks")]
        TipsTricks = 30,

        [Description("Hazardous Goods Data")]
        Hazards = 40
    }

Now that you have friendly descriptions assigned to each enum, and an extension built to the Enum data type, it’s a simple matter to render those friendly names in a dropdown list.

foreach (DigitalAssetType dType in Enum.GetValues(typeof(DigitalAssetType)))
{
    list_AssetTypes.Items.Add(new ListItem(dType.GetDescription(), ((int)dType).ToString()));
}