Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you bind an Enum to a DropDownList control in ASP.NET?

Tags:

c#

.net

asp.net

People also ask

How do you create a DropDownList from an enum in ASP NET MVC?

Run the application and we get the results as in Figure 1.1. I create an HTML Helper extension method to populate a dropdown list using an enum. Create an extension method EnumDropDownListFor in the Extension class under the Models folder. Create a model (ActionTypeModel class) under the Models folder.

How do I find the enum value of a razor view?

You could use ajax to post the value to the server and return the text value. Or you could pass a collection/dictionary or the enums int and name values to the view and convert it to a javascript array and search that array for the corresponding value.


I probably wouldn't bind the data as it's an enum, and it won't change after compile time (unless I'm having one of those stoopid moments).

Better just to iterate through the enum:

Dim itemValues As Array = System.Enum.GetValues(GetType(Response))
Dim itemNames As Array = System.Enum.GetNames(GetType(Response))

For i As Integer = 0 To itemNames.Length - 1
    Dim item As New ListItem(itemNames(i), itemValues(i))
    dropdownlist.Items.Add(item)
Next

Or the same in C#

Array itemValues = System.Enum.GetValues(typeof(Response));
Array itemNames = System.Enum.GetNames(typeof(Response));

for (int i = 0; i <= itemNames.Length - 1 ; i++) {
    ListItem item = new ListItem(itemNames[i], itemValues[i]);
    dropdownlist.Items.Add(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();

I use this for ASP.NET MVC:

Html.DropDownListFor(o => o.EnumProperty, Enum.GetValues(typeof(enumtype)).Cast<enumtype>().Select(x => new SelectListItem { Text = x.ToString(), Value = ((int)x).ToString() }))

My version is just a compressed form of the above:

foreach (Response r in Enum.GetValues(typeof(Response)))
{
    ListItem item = new ListItem(Enum.GetName(typeof(Response), r), r.ToString());
    DropDownList1.Items.Add(item);
}

public enum Color
{
    RED,
    GREEN,
    BLUE
}

Every Enum type derives from System.Enum. There are two static methods that help bind data to a drop-down list control (and retrieve the value). These are Enum.GetNames and Enum.Parse. Using GetNames, you are able to bind to your drop-down list control as follows:

protected System.Web.UI.WebControls.DropDownList ddColor;

private void Page_Load(object sender, System.EventArgs e)
{
     if(!IsPostBack)
     {
        ddColor.DataSource = Enum.GetNames(typeof(Color));
        ddColor.DataBind();
     }
}

Now if you want the Enum value Back on Selection ....

  private void ddColor_SelectedIndexChanged(object sender, System.EventArgs e)
  {
    Color selectedColor = (Color)Enum.Parse(typeof(Color),ddColor.SelectedValue
  }