Skip to content

Instantly share code, notes, and snippets.

@dagda1
Created November 12, 2010 11:04
Show Gist options
  • Select an option

  • Save dagda1/673982 to your computer and use it in GitHub Desktop.

Select an option

Save dagda1/673982 to your computer and use it in GitHub Desktop.
public static class DropDownListForExtensions
{
public static IEnumerable<SelectListItem> EnumToSelectList<TEnum>(this TEnum enumObj, string defaultItem = null) where TEnum : struct
{
if (!typeof(TEnum).IsEnum) throw new ArgumentException("An Enumeration type is required.", "enumObj");
var list = new List<SelectListItem>(from TEnum e in Enum.GetValues(typeof(TEnum))
select new SelectListItem{Value = e.ToString(), Text = System.Text.RegularExpressions.Regex.Replace(
e.ToString(),
"([A-Z])",
" $1",
System.Text.RegularExpressions.RegexOptions.Compiled).Trim()
});
if(!string.IsNullOrEmpty(defaultItem))
list.Insert(0, new SelectListItem{Value = "-1", Text= defaultItem});
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment