Thursday, November 29, 2012

ASPX GridView Sorting with VB



Protected Property SortField() As String
        Get
            If IsNothing(ViewState("SortField")) Then
                ViewState("SortField") = ""
            End If
            Return ViewState("SortField")
        End Get
        Set(ByVal value As String)
            Dim field As String = ""
            Dim dir As String = ""
            If IsNothing(ViewState("SortField")) Then
                ViewState("SortField") = ""
                field = ""
            Else
                field = CStr(ViewState("SortField"))
                If field.Length > 4 Then
                    dir = Right(field, 4).Trim
                    field = Left(field, field.Length - 4).Trim
                End If
            End If
            If value = field Then
                If dir = "ASC" Then
                    ViewState("SortField") = value + " DESC"
                Else
                    ViewState("SortField") = value + " ASC "
                End If
            Else
                ViewState("SortField") = value + " ASC "
            End If
        End Set
    End Property


Protected Sub GridView1_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles GridView1.Sorting
        SortField = e.SortExpression
        bindGridView1()
    End Sub


Sub bindGridView1()
        Dim SQL As String=session("orignal_sql_string")
        If SortField.ToString() <> "" Then
            SQL = SQL & "order by " & SortField.ToString()
        Else
            ' SQL = SQL & "order by form_idx ASC "
        End If
        Try
            Dim ds As DataSet = GetTableData(SQL)
            GridView1.DataSource = ds
            GridView1.DataBind()
           Catch ex As Exception
            '  lbErrorMessage.Text = ex.Message
        End Try
End Sub


No comments:

Post a Comment