using …

Pure C#

DropDownLists with Enums as DataSource

Yazan: esersahin 10/10/2008

http://developcode.blogspot.com/2006/12/dropdownlists-with-enums-as-datasource.html

When creating DropDownLists out of enums in ASP.NET, I often tend to dislike the way the usual examples use the enum’s Values and Names as keys and values for the DropDownList. In this example, I have created an enhanced enum using DescriptionAttribute instead. This way, you can go a lot further on deciding what the visible values in a DropDownList may be – without being tied to a C# type name syntax.

This way, you can get these kinds of DropDownLists using pure enums only:

Step 1 – Enhance your enums with the Description:


using System.ComponentModel;

public enum CourierCompanies
{
[Description("Please select a courier company")]
None = -1,

[Description("Other")]
Other = 0,

[Description("DHL")]
DHL,

[Description("Action Courier")]
ActionCourier,

[Description("American Courier Express")]
ACE

}


Step 2: Create a helper class which extracts description data both for each enum value and a key/value pair for use in DataSources:


using System.ComponentModel;
using System.Reflection;

public class EnumDescription
{
/// <summary>
/// Get the description attribute for one enum value
/// </summary>
/// <param name=”value”>>Enum value
/// <returns>The description attribute of an enum, if any</returns>
public static string GetDescription(Enum value)
{
FieldInfo fieldInfo = value.GetType().GetField(value.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
return (attributes.Length > 0) ? attributes[0].Description : value.ToString();
}

/// <summary>
/// Gets a list of key/value pairs for an enum, using the description attribute as value
/// </summary>
/// <param name=”enumType”>>typeof(your enum type)
/// <returns>A list of KeyValuePairs with enum values and descriptions</returns>
public static List<KeyValuePair;<string, string>> GetValuesAndDescription(System.Type enumType)
{
List<KeyValuePair><string, string>> kvPairList = new List<KeyValuePair<string, string>>();

foreach (Enum enumValue in Enum.GetValues(enumType))
{
kvPairList.Add(new KeyValuePair<string,string>(enumValue.ToString(), GetDescription(enumValue)));
}

return kvPairList;
}
}


Step 3: Fill the DropDownList using the enum itself as a DataSource:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlCourier.DataSource = EnumDescription.GetValuesAndDescription(typeof(CourierCompanies));
ddlCourier.DataTextField = “Value”;
ddlCourier.DataValueField = “Key”;
ddlCourier.DataBind();
}
}

The reason for using the names “Value” and “Key” is that the properties of the generic KeyValuePair type are “Value” and “Key”.