This is how I worked on the problem of binding a sort expression.
Instead of setting the SortExpression name of the real property, I set it to the ordinal position of the column.
<Columns> <asp:TemplateField HeaderText="Name" SortExpression="1" > <ItemTemplate> <%# Item.Name %> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Job Title" SortExpression="2" > <ItemTemplate> <%# Item.JobTitle %> </ItemTemplate> </asp:TemplateField> </Columns>
Then attach the handler to the gridview Sorting event.
<asp:GridView runat="server" OnSorting="Sorting" ...
One of the arguments to the event is the sort expression that you defined earlier (that is, "1" or "2" ). You can use this value to programmatically re-associate the sort expression with the actual property name.
Note : following this approach means refusing to automatically switch between sorting in ascending / descending order. It is not particularly difficult to repeat, though.
Note I use a reflection-based approach to determine property names at runtime.
protected void Sorting(object sender, GridViewSortEventArgs e) { int columnPosition; if (!int.TryParse(e.SortExpression, out columnPosition)) { return; } switch (columnPosition) { case 1: e.SortExpression = Reflector.GetPropertyName<Employee>(o => o.Name); break; case 2: e.SortExpression = Reflector.GetPropertyName<Employee>(o => o.JobTitle); break; } var grid = (GridView)sender; if (grid.SortExpression == e.SortExpression) { if (grid.SortDirection == SortDirection.Ascending) { e.SortDirection = SortDirection.Descending; } } }
Finally, here is my code for the Reflector class, which I use in the above example.
source share