Skip to content

Instantly share code, notes, and snippets.

@ChrisMcKee
Created January 4, 2013 14:01
Show Gist options
  • Select an option

  • Save ChrisMcKee/4452779 to your computer and use it in GitHub Desktop.

Select an option

Save ChrisMcKee/4452779 to your computer and use it in GitHub Desktop.
Dropdown List from Enum (webforms)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web.UI.WebControls;
public static class Helpers
{
public static IEnumerable<ListItem> EnumDropDown<T>()
{
foreach (var name in Enum.GetNames(typeof(T)))
{
var enumType = (T)Enum.Parse(typeof(T), name);
var field = enumType.GetType().GetField(enumType.ToString());
var attributes = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false);
var itemText = attributes.Length > 0 ? attributes[0].Description : enumType.ToString();
yield return new ListItem(itemText, name);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment