Click here to download the source code for this lesson.
The SqlDataSource server control can make your GridView control easily allow data sorting for the end user of your web application without writing any C# code. For example, if you are showing the results of a query on a web page and you want the user to be able to sort one of the columns in ascending or descending order.
First, you should have established a binding between the GridView control and an SqlDataSource control on your web form. Refer to the prior lesson Retrieving database data with the ASP.NET SqlDataSource and GridView controls to learn how to do that if you haven’t already.
Next, set the AllowSorting property of your GridView to True. Then you need to edit the columns in your GridView. Go to each column that you want to make sortable and set the SortExpression property to the name of the column in the SQL query. In my example I wanted to make the Last Name column sortable in my GridView so I set the SortExpression to last_name which is the name of a column in my database query. When you set this property of a column in your GridView ASP.NET will show a hyperlink on the column header of the grid when the application runs. The user can click on the column header hyperlink to sort the data in ascending or descending order.
Click here to watch an example video where I setup sortable columns in my GridView control.