Daily Archives: 2007-10-30

Databind a ComboBox to an Enum and your business object

Databinding intelligently in .net is usually pretty easy. Recently I wanted to quickly bind a combobox where the items are the values of an enum made up of single words and the selected value is tied to my data object. I was surprised that it wasn’t all that straighforward. Here’s me saving you some time in the future.

What you want is an easy way to get a list of objects that you can bind the combobox to. Here is a list you can easily create from any enum that will give you a handle on the names and values of the enum.

code:

public class ComboEnumList <V> : List < keyvaluepair < string,V> >
where V: struct //at least we can constrain that it ain't a class
{
public ComboEnumList():base()
{
//because generics don't allow a constraint like "where V: enum"
if (!typeof(V).IsEnum) throw new Exception( "New Argument Not An Enum " + (typeof(V).FullName));
Array values = Enum.GetValues(typeof(V));
foreach (object value in values)
{
this.Add(new KeyValuePair(Enum.GetName(typeof(V),value), (V) value));
}
}
}

To use this, you’d inherit an instance of this class with type V = your enum.
code:

public class AvailableJerseyStyles : ComboEnumList
{}
public enum JerseyStyleEnum{
Stripes,
Diamonds,
Paisley,
CheckerBoard,
Houndstooth
}

Now go into the VS2k5 designer, add a new project data source based on your AvailableJerseyStylesClass. On instantiation, create the AvailableJerseyStyles object and set it as the datasource for your bindingsource. DisplayMemeber = “Key”, ValueMember = “Value”.
Bind the enum property of your business object datasource to the SelectedValue of the AvailableJerseyStylesClass and you are good to go.

Hope it helps.