Binding Databound controls to Enum

The other day I was curious to bind a static enum list to any databound control in .NET 2.0. The enum might be part of your business object in the middle tier. I did some research on this and found that is pretty easy and intuitive. Let’s see a example:


public enum ApartmentTypes
{
Studio,
OneBedroom = 1,
TwoBedroom = 2,
ThreeBedroom = 3
}

All user defined enums extend System.Enum class. So, to bind DropDownList control to ApartmentTypes enum, the code looks like this:


if (!Page.IsPostBack)
{
DropDownList1.DataSource = Enum.GetNames(typeof(ApartmentTypes));
DropDownList1.DataBind();
}

This code will bind to the enum directly and looking at the page source reveals that both the text and value for each entry in the Dropdownlist control is the same. Since no two entries will have the same entry, this shouldn’t cause any trouble. But, ideally the value should have the actual enum values and not the text to enable us to do more processing when doing a postback. To get the value for the entry selected in the dropdownlist, we should use the Parse method in the Enum class.


int value = (int)Enum.Parse(typeof(ApartmentTypes), DropDownList1.SelectedItem.Text);

This is the final code:

if (!Page.IsPostBack)
{
DropDownList1.DataSource = Enum.GetNames(typeof(ApartmentTypes));
DropDownList1.DataBind();
}
else
{
Response.Output.WriteLine((int)Enum.Parse(typeof(ApartmentTypes), DropDownList1.SelectedItem.Text));
}

Advertisements

One Response to “Binding Databound controls to Enum”

  1. Awesome info. Really really helpful.

    Thanks.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: