Let\'s say I have the following simple enum:
enum Response
{
Yes = 1,
No = 2,
Maybe = 3
}
How can I bind this enum to a DropDow
ASP.NET has since been updated with some more functionality, and you can now use built-in enum to dropdown.
If you want to bind on the Enum itself, use this:
@Html.DropDownList("response", EnumHelper.GetSelectList(typeof(Response)))
If you're binding on an instance of Response, use this:
// Assuming Model.Response is an instance of Response
@Html.EnumDropDownListFor(m => m.Response)
public enum Color
{
RED,
GREEN,
BLUE
}
ddColor.DataSource = Enum.GetNames(typeof(Color));
ddColor.DataBind();
Both asp.net and winforms tutorial with combobox and dropdownlist: How to use Enum with Combobox in C# WinForms and Asp.Net
hope helps
Check out my post on creating a custom helper "ASP.NET MVC - Creating a DropDownList helper for enums": http://blogs.msdn.com/b/stuartleeks/archive/2010/05/21/asp-net-mvc-creating-a-dropdownlist-helper-for-enums.aspx
You can do this a lot shorter
public enum Test
{
Test1 = 1,
Test2 = 2,
Test3 = 3
}
class Program
{
static void Main(string[] args)
{
var items = Enum.GetValues(typeof(Test));
foreach (var item in items)
{
//Gives you the names
Console.WriteLine(item);
}
foreach(var item in (Test[])items)
{
// Gives you the numbers
Console.WriteLine((int)item);
}
}
}
Use the following utility class Enumeration
to get an IDictionary<int,string>
(Enum value & name pair) from an Enumeration; you then bind the IDictionary to a bindable Control.
public static class Enumeration
{
public static IDictionary<int, string> GetAll<TEnum>() where TEnum: struct
{
var enumerationType = typeof (TEnum);
if (!enumerationType.IsEnum)
throw new ArgumentException("Enumeration type is expected.");
var dictionary = new Dictionary<int, string>();
foreach (int value in Enum.GetValues(enumerationType))
{
var name = Enum.GetName(enumerationType, value);
dictionary.Add(value, name);
}
return dictionary;
}
}
Example: Using the utility class to bind enumeration data to a control
ddlResponse.DataSource = Enumeration.GetAll<Response>();
ddlResponse.DataTextField = "Value";
ddlResponse.DataValueField = "Key";
ddlResponse.DataBind();