Sunday, January 13, 2008

Enum To Collection: Make Binding Easy

I prefer storing domain data for applications in an Enum, when that data seldom/rarely changes. In doing so, I find that I need to display this data in the form of a DropDownList in the UI. Through a generic "Enum To Collection" method, and the use of ObjectDataSources, this task is very easy.

Here is the generic static method to turn an Enum into a Collection:


public static Collection<KeyValuePair<string, int>> ToCollection<T>()



{



Collection<KeyValuePair<string, int>> collection = new Collection<KeyValuePair<string, int>>();







Array values = Enum.GetValues(typeof (T));







foreach (int value in values)



{



collection.Add(new KeyValuePair<string, int>(Enum.GetName(typeof (T), value), value));



}







return collection;



}

I then define a static method in my business class decorated with the DataObject attribute:


[DataObjectMethod(DataObjectMethodType.Select)]



public static Collection<KeyValuePair<string, int>> GetDays()



{



return EnumHelper.ToCollection<Days>();



}
Then, just drop a DropDownList control onto your page. Use the Configure Data Source wizard to select your static method you just defined:



And that's it. Check it out:




Note: I like to set "AppendDataBoundItems" to true, and add my "-Select-" value on the page. This is nice because I don't have to deal with that logic in my business tier.

Hope you like it and happy binding.

No comments:

Post a Comment