How to Sort Grid View Columns Programmatically
Author: DevASP Team
Download Source Code : 704_DataGrid_DataView.zip
In this article I will try to explain you how you can sort GridView column programmatically using DataView.
During application development many times developer used to face scenarios in which resending the data back to database and apply “ORDER BY” clause and get data back again. Some times this strategy makes the execution slow. In ASP.Net 2.0 we have a DataView “SORT” property that solves this problem easily and effectively. A sample application will provide you the idea that how you can use this property.
To begin with this create a new application add a GridView Control. I am assuming that your database is already exists so I am not going into the details of Database procedures. Your .aspx page code will be look like this:
Now in .aspx.cs file add the following code in page load event. You can also create a separate methods or functions but here I am adding all in same event that is on PAGE LOAD event.
Create new connection object and add connection string. Fill SqlDataAdapter with result set and using its FILL method add the result set to Data Table new use the following command to sort your result set:
This will sort you ENAME column by default Ascending. Your whole code to execute the basic of DataView sorting is as follows: