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 .

How to sort ASP.NET DropDownList based on DataValueField or DataTextField using LINQ?

Sorting ASP.NET Dropdown list is very common requirement for any of the web application development.  To Implement this features sometimes developers used to iterate through each and every item and create a sorted list of element then reassign the same source to dropdownlist or sort the element at source itself. But this thing can be done easily using LINQ. In this post I am going describe how you can sort a ASP.NET DropDownList based on either of DataTextField or DataValueField using LINQ and list of KeyValuePair elements as DataSource.

To start with the application, let’s consider you have following List of employee data as datasource of the DropDownList.

 /// <summary>
 /// Create List Of Employee
 /// </summary>
 List<KeyValuePair<int, string>> employees = new List<KeyValuePair<int, string>>
        {        new KeyValuePair<int,string>(1,"Abhijit"),
                  new KeyValuePair<int,string>(2,"Rahul"),
                  new KeyValuePair<int,string>(3,"Kunal"),
                  new KeyValuePair<int,string>(4,"Atul"),
                 new KeyValuePair<int,string>(5,"Abhishek"),
        };
 

In the employee list collection, you have added KeyValuePair for each element, where Key is employee ID and Value is the employee name.  The most interesting part of using KeyValuePair is you can bind either of Key or Value with the DropDownList as per your requirement

Now let’s bind the DropDownList with the DataSource