Click here to Skip to main content
14,975,234 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I’m trying to implement a Sort feature for my GridView that is being populated from a DataTable. Also I have a Filter/Search feature so I can’t use ViewState cause every time the Filter /Search results are displayed and I try to Sort them the Sort displays all the records then Sorts them.

This is the only code that I found that doesn't use a ViewState but, it doesn't work. Whenever I click on the column hearder nothing happens. Just my message 'Empty' pops-ups.
VB
Private Function ConvertSortDirectionToSql(ByVal sortDirection As SortDirection) As String
        Dim newSortDirection As String = String.Empty

        Select Case SortDirection
            Case SortDirection.Ascending
                newSortDirection = "ASC"

            Case SortDirection.Descending
                newSortDirection = "DESC"
        End Select

        Return newSortDirection
    End Function

    Protected Sub grdNurseVisits_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs) Handles grdNurseVisits.Sorting

        Dim dtable As DataTable = TryCast(grdNurseVisits.DataSource, DataTable)

        If Not dtable Is Nothing Then
            MsgBox("Not Empty")
            Dim dataView As DataView = New DataView(dtable)
            dataView.Sort = e.SortExpression & " " & ConvertSortDirectionToSql(e.SortDirection)

            grdNurseVisits.DataSource = dataView
            grdNurseVisits.DataBind()
        ElseIf dtable Is Nothing Then
            MsgBox("Empty")
        End If
    End Sub
Posted
Updated 18-Nov-13 9:14am
v2

Is this a Windows or web app? DataGridView is Windows, but you're talking about ViewState, so I assume you've got a web app with a GridView. Assuming that's the case, you're getting your "Empty" message every time because your grid's data source is nothing on postback (which is normal). If you want access to the data source, add it to ViewState at the same time you bind it, and then fetch it out here in the sort handler. And this will also address your primary question: when you apply your sort, you are rebinding, so you need to preserve and re-apply any filter that is present as well. Something like this:

VB
Using dv As New DataView(ViewState(MY_DATA))
    dv.Sort = e.SortExpression & " " & ConvertSortDirectionToSql(e.SortDirection)
    ViewState(MY_SORT) = dv.Sort
    If ViewState(MY_FILTER) IsNot Nothing Then dv.RowFilter = ViewState(MY_FILTER) 'preserve current filter
    grdNurseVisits.DataSource = dv
    grdNurseVisits.DataBind()
End Using
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900