I was recently trying to sort an ASP.NET gridview and realized it was no easy task to show the column that the grid was sorted by. I don’t know if 4.0 or 4.5 .NET has this capability, but it seems like the GridView control should have parameters that you could assign an ascending/descending icons to. Unfortunately, it doesn’t.
In a few lines of code I was able to add an image next to the column header like the example above (see that little triangle?). I was amazed on what I found online when researching this. Many developers have a tendency of over-complicating things, so my code below is as bare-bones as possible.
VB.NET (Code-Behind on GridView RowCreated Event):
If e.Row.RowType = DataControlRowType.Header Then For Each field As DataControlField In gv1.Columns If field.SortExpression = gv1.SortExpression Then Dim sortImage As New Image() If gv1.SortDirection.ToString = "Ascending" Then sortImage.ImageUrl = "images/asc.png" Else sortImage.ImageUrl = "images/desc.png" End If sortImage.AlternateText = "Sorted " & gv1.SortDirection.ToString e.Row.Cells(gv1.Columns.IndexOf(field)).Controls.Add(sortImage) End If Next End If
It’s assumed you already have a GridView databound to an object datasource and you have sorting enabled. This code-behind should be under the gridview (gv1) RowCreated event.
- 1 – Checks if the row being generated is a header row (otherwise, the row is ignored)
- 2 – Sets up a loop to go through each cell, or field, in the row
- 3 – Checks if the sort expression of the GridView matches the current field/column
- If the sort expression matched – enter lines 4 – 11
- 4 – Creates a new image object called ‘sortImage’
- 5 – 9 – Tests the GridView’s current sort direction. If it’s ‘Ascending’, assign an ImageUrl (you need ascending/descending icons – mine are in my ‘/images’ folder). Otherwise, assign the descending image to the ImageUrl
- 10 – Sets ALT text to the image so we keep W3C compliance – Mine is a concatenated string that would be something like ‘Sorted Descending’
- 11 – Adds the image to the header cell
I hope this helps someone out there. I know there are many ways to do this, but this seemed to be the most light-weight scenario I could come up with without using a third-party solution.