Sorting within gridview without any data binding control - how to do it?
-
01-10-2019 - |
Question
I have a GridView control on my page. GV doesn't use any .net control as a data source to bind to data. I'm doing this in code behind where I'm creating my own DataTable and DataSet. Then I'm binding this DataSet to GV. Next i would like to enable of sorting colums. The issue is that this doesn't work as it should when you don't use any predefined data source control. You have to write some code. Bud I don't know what code, how to sort GV after user clicks heder? Then rows shoud be sorted by the data within this column. And how to enalbe ascending and descending sort by clicking the same link?
Solution
Set AllowSorting=True and handle Sorting event. In sorting event, you can toggle sort direction if the sort expression is the same (i.e. you are clicking on same column header again). See this article for quick start.
OTHER TIPS
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