Learn ASP.NET MVC, ASP.NET Core, and Design Patterns through our online training programs. Courses conducted by Bipin Joshi on weekends. Read more details here.

Sorting Template Columns of ASP.NET DataGrid

Introduction

ASP.NET DataGrid allows you to sort columns based on certain sort expression. For simple data bound columns whenever you click on the column header automatically SortCommand event is raised which allows you to bind the grid with sorted data. However, template columns do not raise this event automatically. There are certain tricks that you need to play in order to make it happen. This article shows how to do just that.

Creating your DataGrid

In order to follow the example given in this article you need to create a DataGrid that will be bound to Employees table of Northwind database. Place a DataGrid on the web form and add a template column to it. The column will display LastName field of the table. First of all set AllowSorting property of the DataGrid to True. Unless this property is turned on, sorting feature will not be enabled.

Creating Template Column

Now that you have DataGrid in place, add a template column to it. In the HeaderTemplate add a LinkButton. This button will allow user to sort the column. In the case of normal bound columns you use SortExpression property to specify the expression on which the column is to be sorted. However, in case of template columns this does not work. To overcome this set CommandName property of the LinkButton to "sort" and CommandArgument property to sort expression (LastName in our case). Once this is done add a Label in the ItemTemplate and bind it with LastName field using <%# and %> syntax.

Handling SortCommand Event

When you run the web form and click on the LinkButton, SortCommand event will be raised. Note that this event gets raised because we set CommandName property of LinkButton to "sort". Inside the SortCommand Event you can retrieve sort expression using e.SortExpression property.

Sample Source Code

Sample source code is provided with this article that illustrated above technique of sorting DataGrid template columns.

I hope you must have find this article useful




Bipin Joshi is a software consultant, trainer, author and a yogi having 21+ years of experience in software development. He conducts online courses in ASP.NET MVC / Core, jQuery, AngularJS, and Design Patterns. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced Yoga way of life he also teaches Ajapa Meditation to interested individuals. To know more about him click here.

Get connected : Twitter  Facebook  Google+  LinkedIn

Posted On : 09 Oct 2002



Tags : ASP.NET Web Forms Server Controls Data Controls