This post originated from an RSS feed registered with .NET Buzz
by Doug Thews.
Original Post: Adding Sort Arrows to Your DataGrid Header Columns
Feed Title: IlluminatiLand
Feed URL: http://apps5.oingo.com/apps/domainpark/domainpark.cgi?client=netw8744&s=JETBRAINS.COM
Feed Description: A technology blog for people enlightened enough to think for themselves
Let's assume that you have a DataGrid defined that's bound
to a data source with "name" in the first column (element 0) and
"state" in the 6th column (element 5), and you want to be able to
sort on those columns. While enabling sorting is easy and responding
to the click for the item header is very straightforward, the UI
doesn't present (by default) a way to tell the user what's being
sorted and whether it's ascending or descending.
Here's my way of doing that. I keep a sort field property around
in the page that let's me know what field was being sorted. I stash
this information off on the SortCommand event.
Protected Sub DataGrid_Sort _
(ByVal sender As System.Object, _
ByVal e As DataGridSortCommandEventArgs) _
Handles DataGrid.SortCommand
' Save the old sort field
Dim strCurrentSortField As String = SortField
' Save the new sort expression (column sort name)
SortField = e.SortExpression.ToString()
If (strCurrentSortField.Equals(SortField)) Then
SortAscending = Not SortAscending
Else
SortAscending = True
End If
' Change to the first page for the new sort
DataGrid.CurrentPageIndex = 0
' Now, re-bind the Data Grid to reflect the new sort
BindDataGrid()
End Sub
Now, I can use the ItemDataBound event to add an Up or Down arrow
to the header column that's being sorted. I use the 5/6 character
of the WebDings font to accomplish this. Remember, the
ItemDataBound event is called for every row that's bound
to the grid, so I need to check and make sure to add my special
control to just the header.
Protected Sub DataGrid_ItemDataCreated _
(ByVal sender As System.Object, _
ByVal e As DataGridItemEventArgs) _
Handles DataGrid.ItemDataBound
Dim strSortField As String
Dim boolSortAscending As Boolean
Dim lblSortArrow As Label
Dim Cell As TableCell
Dim strOldString As String
' Add arrow to currently sorted column
Select Case e.ListItem.ItemType
Case ListItemType.Header
strSortField = SortField
boolSortAscending = SortAscending
lblSortArrow = New Label()
lblSortArrow.Font.Name = "Webdings"
If SortAscending Then
lblSortArrow.Text = "6"
Else
lblSortArrow.Text = "5"
End If
Select Case strSortField
Case "name";
Cell = e.Item.Cells(0)
Case ""
' If blank, then use the default sort (name)
Cell = e.Item.Cells(0)
Case "state"
Cell = e.Item.Cells(5)
End Select