Thursday, June 11, 2009

How to get the values of an enum?

Submit this story to DotNetKicks

Sometimes you need to list the values of your enums. Typically, I have to represent them in dropdown-boxes for a web page. Here's my solution:

public static ListItem[] GetEnumValues(Type t)

{

List<ListItem> lc = new List<ListItem>();

lc.Add(new ListItem() { Text = "Choose an item", Value = "-1" });

if (t.UnderlyingSystemType.BaseType == typeof(System.Enum))

{

foreach (int value in Enum.GetValues(t))

{

lc.Add(new ListItem() { Text = Enum.GetName(t, value), Value = value.ToString() });

}

}

return lc.ToArray();

}


Then, to use it in a control, use the Items.AddRange() function:

_dropdown.Items.AddRange(SomeClass.GetEnumValues(typeof(myEnumType)));

Plain and easy, but as far as I know, not available directly from .NET.

2 comments:

Anonymous said...

Hi,

If you change this line
GetEnumValues(Type t)

to

GetEnumValues(Enum enumType)

Then you don't need to do:
if (t.UnderlyingSystemType.BaseType == typeof(System.Enum))

Yngve B. Nilsen said...

@Anonymous

Unfortunately, that's not right. Enum.GetValues does not accept a variable of type Enum. So this means you need to do a lot of different things instead of the line you're suggesting to remove.

With your example you'd need to instanciate the Enum before passing it into the GetEnumValues, and you'd have to change the foreach-loop to do Enum.GetValues(enumType.GetType());

In Stians example, you will not have to instanciate the enum, and since we don't need a particular instance of the Enum to get its values or names, we really just need the type. Hence Type t :)