Here are some snippets I've used. It's nice when the 3:rd click on the same header removes the sorting on that column and also promotes the columns of a lower sortorder, than the removed sortexpression, to a higher sortorder, such here and here.
Protected Sub SortLinkBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim gv As GridView = CType(sender.parent.parent.parent.parent, GridView)
Call UpdateTabPanelProgressSpinner(gv)
Dim dv As New DataView
dv = gv.DataSource
Call BuildSortExprTable("sort" + gv.ID, sender.commandname)
dv.Sort = CurrSortExpressions("sort" + gv.ID)
gv.DataSource = dv
gv.DataBind()
End Sub
Protected Function BuildSortExprTable(ByVal vsName As String, ByVal vsKey As String) As Dictionary(Of String, String)
Dim SortTable As Dictionary(Of String, String)
SortTable = IIf(ViewState(vsName) Is Nothing, New Dictionary(Of String, String), CType(ViewState(vsName), Dictionary(Of String, String)))
If SortTable.Count = 0 Then
SortTable.Add(vsKey, " ASC")
Else
If SortTable.ContainsKey(vsKey) Then
Select Case SortTable(vsKey).ToString
Case " ASC"
SortTable(vsKey) = " DESC"
Case " DESC"
SortTable.Remove(vsKey)
End Select
Else
SortTable.Add(vsKey, " ASC")
End If
End If
ViewState.Add(vsName, SortTable)
Return SortTable
End Function
Protected Function CurrSortExpressions(ByVal vsName As String) As String
Dim SortTable As Dictionary(Of String, String)
SortTable = IIf(ViewState(vsName) Is Nothing, New Dictionary(Of String, String), CType(ViewState(vsName), Dictionary(Of String, String)))
Dim sSorts As String = String.Empty
Dim key As Object
For Each key In SortTable.Keys
sSorts += ", " + key.ToString() + " " + SortTable(key).ToString()
Next
'remove first ", "
If sSorts = "" Then
'nada
Else
sSorts = Right(sSorts, sSorts.Length - 2)
End If
Return sSorts
End Function