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