Filling Lists with Enum Values

There have been many times where I've needed to fill a drop down list / list box etc with the values of some Enum class in C# / .net . The fact that this tends to be a repeatable task prompted me to look for a reusable method that would do just that - get me an array of ListItems, deduced from a list of Enums that I could whack into my lists.

Fortunately, this is a very simple solution. Most of the items behind list can be filled with an array of values using the .AddRange() method.

public static ListItem[] GetListItems<T>()

{

    ListItem[] listItemArray = new ListItem[Enum.GetValues(typeof(T)).Length];

 

    for(int i=0; i<listItemArray.Length; i++)

    {

        T value = (T)Enum.GetValues(typeof(T)).GetValue(i);

 

        short numValue = Convert.ToInt16(Enum.Parse(typeof(T), value.ToString()));

        string text = Translate.Message(StringHelper.SplitTitleCase(((T)value).ToString()));

 

        listItemArray[i] = new ListItem(text, numValue.ToString());

    }

    return listItemArray;

}

What this method will do is accept the type T of your Enum, and return to you an array of ListItems (that you can send as a parameter into your AddRange() method). One note I'd like to make is that this method uses a home-made String utility class method (StringHelper.SplitTitleCase) which converts strings of text from something like "AStringOfText" to "A String Of Text".

An example on how to use this method is pretty simple. Say I have a drop down list that I want to fill with enum values from my DateRangeType (which contains things like: "LastWeek", "Last Month" etc). I simply have to call GetListItems with the type of this Enum:

ddlPeriod.Items.AddRange(GetListItems<DateRangeType>());

Simple & reusable. I'm a lazy programmer in that I hate having to do the same thing more than once. Anytime you can cut corners and reduce the amount of code you have to write, then all the better for you and your company.

 

posted @ Wednesday, November 07, 2007 7:32 AM

Print

Comments on this entry:

# re: Filling Lists with Enum Values

Left by Dennis Decoene at 8/5/2008 8:07 PM
Gravatar
Well done. I'm an even lazier programmer than you are so it seems. Instead of writing it myself, I googled for it ;)

# re: Filling Lists with Enum Values

Left by Xabatcha at 10/19/2008 10:53 PM
Gravatar
I guess this is very nice candidate on extension method, isn't it?

Your comment:



 (will not be displayed)


 
 
 
Please add 5 and 6 and type the answer here:
 

Live Comment Preview:

 
«November»
SunMonTueWedThuFriSat
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456