Binding an Enum to a List Control
At work we use a fair amount of enumerators in our code to define the values for lookup tables in the database. This a great way to implement these values because it avoids magic numbers and is easier to read and to maintain. But as much as I like working with enumerators, I’ve always struggled with the fact that I couldn’t bind them to list controls in the UI. Essentially there are 2 options you have to accomplish this:
1) Hard code the enumerated values into the list control – this is obviously a bad idea.
2) Just get the values from the DB since they are synchronized anyway – This idea actually works pretty well especially if you have a good caching mechanism in place
Even though #2 isn’t a terrible solution, it still bothered me to have to go to the DB to get values I already have defined in code. So I took a little time yesterday and wrote a method to populate a list control with the values of an enumerated type. Here is the code, note the last parameter will break apart your enumerator for better display – eg. ThisIsAnEnum will become This Is An Enum in the list control:
///
/// Populates a list based on the values of an enumerator
///
/// Web control to populate
/// An enumeration type
/// If true will break enum value with spaces on case change
public static void PopListFromEnum(ListControl list, System.Type enumType, bool spaceOnCase)
{
list.Items.Clear();
Array vals = Enum.GetValues( enumType);
for(int i = 0; i < vals.Length; i++)
{
string val = vals.GetValue(i).ToString();
string text = val;
if (spaceOnCase)
{
char[] cars = text.ToCharArray( 1, text.Length - 1 );
int offset = 1; // count the fact we are startng at position 1 to start with
for(int x = 0; x < cars.Length; x++)
{
if (Char.IsUpper( cars[x] ))
{
text = text.Insert( x + offset, " " );
offset += 1;
}
}
}
list.Items.Add( new ListItem( text, val ) );
}
}
Once you have the list populated to assign the selected value back out you can do something like this:
object.SomeEnum = (SomeEnum)Enum.Parse(typeof(SomeEnum), ListControl.SelectedValue);

Separating the enum name with spaces is clever for a native application, but what’s your solution for localizing enums?
Yeah, thats a good point Derek. Fortunately for me we dont have to worry about the localization bit. It would definately add some complexity to this solution.