Friday, November 22, 2013

sorting in asp.net gridview

T o achieve the sorting in asp.net gridview

1.make AllowSorting to True in gridview
2.mention SortExpression as datafield name
3.write the following function to get the sort direction

VB Code

Public Property dir() As SortDirection
        Get
            If ViewState("dirState") Is Nothing Then
                ViewState("dirState") = SortDirection.Ascending
            End If
            Return DirectCast(ViewState("dirState"), SortDirection)
        End Get
        Set(ByVal value As SortDirection)
            ViewState("dirState") = value
        End Set
    End Property


Protected Sub gvReport_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvReport.Sorting
        Dim sortingDirection As String = String.Empty
        If dir() = SortDirection.Ascending Then
            dir = SortDirection.Descending
            sortingDirection = "Desc"
        Else
            dir = SortDirection.Ascending
            sortingDirection = "Asc"
        End If

        Dim sortedView As New DataView(ViewState("gv"))
        sortedView.Sort = Convert.ToString(e.SortExpression) & " " & sortingDirection
        gvReport.DataSource = sortedView
        gvReport.DataBind()
    End Sub