Sorting in a GridView is a common scenario required by most of the web applications. In my previous articles I discussed GridView Sorting Using Bound Columns and Sorting GridView with Autogenerated Columns. In both of my previous articles I used the help of DataView object to sort the container. Most of the enterprise applications take advantage of the entity classes which allow the basis for object oriented programming. In this article I will explain how you can sort the GridView control which uses a generic list as its data source.
Introduction:
Sorting in a GridView is a common scenario required by most of the web applications. In my previous articles I discussed GridView Sorting Using Bound Columns and Sorting GridView with Autogenerated Columns. In both of my previous articles I used the help of DataView object to sort the container. Most of the enterprise applications take advantage of the entity classes which allow the basis for object oriented programming. In this article I will explain how you can sort the GridView control which uses a generic list as its data source.
Creating a GridView Control:
Let's first create a GridView control. The GridView will contain two bound columns and two template columns. Take a look at the code below:
<asp:GridView EnableSortingAndPagingCallbacks="false" AllowSorting="true" ID="gvUsers" |
public class User |
public List |
private void BindData() |
Although
you have bind the list to the GridView, the sorting mechanism is not yet
enabled. In order to deal with sorting which is dependent on the list of objects
you will need to create a Comparer which implements the IComparer
interface. The IComparer interface contains a method name CompareTo, which
you can implement to compare the objects.
Implementing the IComparer Interface
We will
create a class called GenericComparer which will implement the IComparer
interface. The GenericComparer class contains bunch of stuff so let's check it
out in detail.
SortDirection : The sort direction indicates
the direction of the sort. This can be ascending or descending.
public SortDirection SortDirection |
GenericComparer
Constructor : The contructor takes two arguments namely, sortExpression and
sortDirection. The sortExpression is the name of the GridView column to sort and
sortDirection denotes the direction in which the column has to be sorted. The
sortDirection can be ascending or descending.
public GenericComparer(string sortExpression, SortDirection sortDirection) |
public int Compare(T x, T y) |
Using the Code
An ideal place to call the sorting
method is inside the GridView_Sorting event which is fired when you clicked the
column header of the GridView control. Take a look at the code below:
protected void gvUsers_Sorting(object sender, GridViewSortEventArgs e) |
Now,
if you click on the GridView header it will be sorted based on what column you
clicked on.
I hope you liked the article, happy coding!