Tuesday, January 25, 2011

Sorting a GridView

Create a property that handles the sort direction of the current page.

Private Property GridViewSortDirection() As SortDirection
        Get
            Return DirectCast(ViewState("SortDirection"), SortDirection)
        End Get
        Set(ByVal value As SortDirection)
            ViewState("SortDirection") = value
        End Set
    End Property

Next, create a function that handles the switching of the sort direction.

Private Function ToggleSortDirection() As String

        Dim retSortDirction As String = String.Empty

        Select Case GridViewSortDirection
            Case SortDirection.Ascending

                GridViewSortDirection = SortDirection.Descending
                retSortDirction = "DESC"

            Case SortDirection.Descending

                GridViewSortDirection = SortDirection.Ascending
                retSortDirction = "ASC"

        End Select

        Return retSortDirction

    End Function

I've also created a page property that stores the data in ViewState. If you are going to do this make sure your data is small.

Private Property dtDataSource() As DataTable
        Get
            Return DirectCast(ViewState("DataTableName"), DataTable)
        End Get
        Set(ByVal value As DataTable)
            ViewState("DataTableName") = value
        End Set
    End Property

Lastly, in the GridView sort command, get your data from the datasource and sort is by the column and sort direction. Finally, databind your GridView.

Protected Sub GridView_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles GridView.Sorting

        Dim dt As New DataTable
        dt = dtDataSource
        Dim dv As DataView
        dv = dt.DefaultView

        dv.Sort = e.SortExpression + " " + ToggleSortDirection()

        Me.GridView.DataSource = dv
        Me.GridView.DataBind()


    End Sub

0 comments:

Post a Comment