Sorting Template Columns of ASP.NET DataGrid
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
is a software consultant, trainer, author, yoga mentor, and spiritual guide having 23+ years of experience in software development, consulting, and training. He conducts instructor-led online training courses
in ASP.NET Core, ASP.NET MVC, and Design Patterns for individuals and small groups. He is a published author and has authored or co-authored books for Apress and Wrox press. Having embraced the Yoga way of life he also teaches Ajapa Yoga
to interested individuals. To know more about him click here
Get connected : Twitter Facebook