Generic Way to Bind Enum With Different ASP.NET List Controls

In this post I am going to explain how we can bind a Enum with ASP.NET List Controls. These comprise of four different types of control, CheckBoxList, DropDownList, ListBox and RadioButtonList. This is one of the common requirements during development to bind a Enum with List Control and challenge is when we need to bind the both text and value.
Let’s consider we have the blow Enum. Now I am going to bind it with all the above mentioned type List Controls.
image

Well, One of the easiest way that we can implement is by Enum.GetNames(Type enumType)which retrieves the name list of enumberation  and Enum.GetValues(Type enumType), which returns the list of values for each names .

Once we have the Names and Values, we can easily bind with any ListControl by just iterating with them.

  public void BindEnumToListControls(Type enumType, ListControl listcontrol)
        {
            string[] names;
            Array values;
            int countElements, upperBound, lowerBound;
            names = Enum.GetNames(enumType);
            values = Enum.GetValues(enumType);
            for (countElements = 0; countElements <= names.Length - 1; countElements++)
            {
                listcontrol.Items.Add(new ListItem(names[countElements].ToString(), values.GetValue(countElements).ToString()));
            }
        }

You will have the below output

image

Now let’s have a quick look on how to call BindEnumToListControls() method, yeah very simple

  protected void Page_Load(object sender, EventArgs e)
        {
            BindEnumToListControls(typeof(CustomerType), DropDownList1);
            BindEnumToListControls(typeof(CustomerType), checkboxlist);
            BindEnumToListControls(typeof(CustomerType), ListBox1);
            BindEnumToListControls(typeof(CustomerType), RadioButtonList1);
        }

image You must be thinking why iterating through each and every names why not using LINQ instead of that.  Well, it’s time to optimized it . Hot smile

The easiest way to do it with LINQ is to convert the enum into Dictionary and Set the DataSource of List. Why Dictionary ? Because we want to bind with both Key and Value Pair for Dropdown list.

  public void BindEnumToListControls(Type enumType, ListControl listcontrol)
        {
            string [] names = Enum.GetNames(enumType);
           List.DataSource = strNames.Select((key, value) =>
                                       new { key, value }).ToDictionary(x => x.key, x => x.value + 1);
            listcontrol.DataTextField = "Key";
            listcontrol.DataValueField = "Value";
            listcontrol.DataBind();
        }

Above code will do the same as we have in the previous output.  But this approach certainly having a small problem . Don't tell anyone smile . If you look into the ViewSource of the above generated html and verify the Value Field for each and every control. All the value field are containing the sequential value.

image

In some certain case, Enum may contain the Value as well, so that time we need to bind the actual value instead of overriding the value while creating the Dictionary as shown in below snippet .

image

I was thinking for some different approach but which leads me using for-each only. Then I look for some solution, and found one very interesting post, which handles this in a smart way.

image

      public void BindEnumToListControls(Type enumType, ListControl listcontrol)
        {
            string [] names = Enum.GetNames(enumType);
            listcontrol.DataSource = Enum.GetValues(typeof(CustomerType)).Cast<Int32>()
                                      .ToDictionary(currentItem =>
                                          Enum.GetName(typeof(CustomerType), currentItem));
            listcontrol.DataTextField = "Key";
            listcontrol.DataValueField = "Value";
            listcontrol.DataBind();
        }

Now from the below image, you can see the Customer Type value is applied to the List elements.

image

Looking for simplest and handy  ways, here is two nice post by Suprotim Agarwal

How to Bind an ASP.NET DropDownList to an Enumeration with two lines of code

How to Bind An Enum Name and Value to an ASP.NET DropDownList

Cheers !
AJ

5 thoughts on “Generic Way to Bind Enum With Different ASP.NET List Controls

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