Gridview sorting with custom template fields Gridview sorting with custom template fields asp.net asp.net

Gridview sorting with custom template fields


I had the same issue, the BoundField was sorting as it should, but the TemplateField did not sort at all.

I changed this:

<asp:TemplateField SortExpression="Category">   <HeaderTemplate>Category</HeaderTemplate>   <ItemTemplate>A value</ItemTemplate></asp:TemplateField>

To this:

<asp:TemplateField HeaderText="Category" SortExpression="Category">   <ItemTemplate>A value</ItemTemplate></asp:TemplateField>

I removed the HeaderTemplate and added the HeaderText in the TemplateField.


Make sure you specify the SortExpression property on the template field

<asp:TemplateField HeaderText="Object Category ID" SortExpression="ObjectCategoryID"><ItemTemplate>    <asp:Label ID="lblItems" runat="server" Text='<%# GetItems((int)DataBinder.Eval(Container.DataItem, "ObjectCategoryID"))%>' /></ItemTemplate></asp:TemplateField>