Ron Harlev
Ron Harlev

Reputation: 16673

Mapping enum values to a drop down (combobox) list in ASP.NET

I have an ASP.NET page with a drop down (asp:DropDownList) control. I also have a defined ENUM

Public Enum myEnumType As Integer
  A
  B
  C
End Enum

I want to define the "value" property of each asp:ListItem with one of the ENUM value (A,B,C represented as a string of course). I also want to assign the "text" value of each to be some unrelated string (e.g "dog","cat","ant").

I would like to use this syntax:

<asp:DropDownList ID="myCombo" runat="server">
  <asp:ListItem Text="cat" Value="<%= myEnumType.A.toString() %>" />
  <asp:ListItem Text="dog" Value="<%= myEnumType.B.toString() %>" />
  <asp:ListItem Text="ant" Value="<%= myEnumType.C.toString() %>" />
</asp:DropDownList>

But using the <%= is not valid in this type of controls.

How can I do this in declarative ASP.NET (not with code behind to create each item)

Upvotes: 1

Views: 2151

Answers (4)

danielovich
danielovich

Reputation: 9687

foreach(var item in Enum.GetValues(typeof(MyEnum)))
{
    lbEnum.Items.Add(new ListItem(Enum.GetName(typeof(MyEnum), item), item.ToString()));
}

Upvotes: 1

j0tt
j0tt

Reputation: 1108

MathewMartin's answer works just seems really inefficient. Wouldn't this be a better/cleaner approach?

string[] names = Enum.GetNames(typeof(MyFavoriteEnum));
int[] values = (int[])Enum.GetValues(typeof(MyFavoriteEnum));
for(int i =0; i<names.Length;i++){
   dropDown.Items.Add(
      new ListItem(
        names[i],
        values[i].ToString()
       )
   );
}

Upvotes: 1

MatthewMartin
MatthewMartin

Reputation: 33143

Why not databind?

enum MyFavoriteEnum { A=1, B=2, C=3 }
for(int i =0; i<Enum.GetNames(typeof(MyFavoriteEnum)).Length;i++)
{
   ListItem li = new ListItem(
       Enum.GetNames(typeof(MyFavoriteEnum))[i],
       ((int)Enum.GetValues(typeof(MyFavoriteEnum)).GetValue(i)).ToString()
       );
    dropDown.Items.Add(li);
} 
// Edited to make it actually work

Upvotes: 0

Vadim
Vadim

Reputation: 21704

The code doesn't make much sense. Why do you use Enum in this case? It's the same like using constants. It looks like you can get away with hard coding values.

<asp:DropDownList ID="myCombo" runat="server">
  <asp:ListItem Text="cat" Value="A" />
  <asp:ListItem Text="dog" Value="B" />
  <asp:ListItem Text="ant" Value="C" />
</asp:DropDownList>

Upvotes: 2

Related Questions