Wednesday, December 7, 2011

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.

 
01public void BindEnumToListControls(Type enumType, ListControl listcontrol)
02      {
03          string[] names;
04          Array values;
05          int countElements, upperBound, lowerBound;
06          names = Enum.GetNames(enumType);
07          values = Enum.GetValues(enumType);
08          for (countElements = 0; countElements <= names.Length - 1; countElements++)
09          {
10              listcontrol.Items.Add(new ListItem(names[countElements].ToString(), values.GetValue(countElements).ToString()));
11          }
12      }
 

You will have the below output

image

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

 
1protected void Page_Load(object sender, EventArgs e)
2      {
3          BindEnumToListControls(typeof(CustomerType), DropDownList1);
4          BindEnumToListControls(typeof(CustomerType), checkboxlist);
5          BindEnumToListControls(typeof(CustomerType), ListBox1);
6          BindEnumToListControls(typeof(CustomerType), RadioButtonList1);
7      }

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.

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

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

 
01public void BindEnumToListControls(Type enumType, ListControl listcontrol)
02  {
03      string [] names = Enum.GetNames(enumType);
04      listcontrol.DataSource = Enum.GetValues(typeof(CustomerType)).Cast<Int32>()
05                                .ToDictionary(currentItem =>
06                                    Enum.GetName(typeof(CustomerType), currentItem));
07      listcontrol.DataTextField = "Key";
08      listcontrol.DataValueField = "Value";
09      listcontrol.DataBind();
10  }
 

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,
original post by
Abhijit Jana

No comments:

Popular Posts