Question

I have an asp gridview which is connected to my sql database via LINQ. I have it bound in the code behind. I also do the usual,

 AllowSorting="True"

and I set the sort expression for each column: ex-

                <asp:BoundField DataField="BorrowerDateOfBirth" HeaderText="Date Of Birth" 
                    DataFormatString="{0:d}" SortExpression="BorrowerDateOfBirth" >
                </asp:BoundField>

But when I run the application, and click the column headers to sort, the application fires an exception error that reads:

"The GridView 'gridview1' fired event Sorting which wasn't handled."

I looked this error up online but I only found responses related to C# code. I tried converting them to vb.net but the error still persisted.

Does anyone know how to handle sorting of an asp gridview in vb.net?

Was it helpful?

Solution

you need to set the OnSorting="" property to some function name, and then handle the sorting in said function. something along these lines

Protected Sub TaskGridView_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)  
    'Retrieve the table from the session object.
    Dim dt = TryCast(Session("table"), DataTable)
    If dt IsNot Nothing Then 
      'Sorting the data.
      dt.DefaultView.Sort = e.SortExpression & " " &  GetSortingDirection(e.SortExpression)
      TaskGridView.DataSource = Session("TaskTable")
      TaskGridView.DataBind()
    End If
End Sub

Private Function GetSortingDirection(ByVal column As String) As String
    ' By default, set the sort direction to ascending.
    Dim sortDirection = "ASC"
    ' Retrieve the last column that was sorted.
    Dim sortExpression = TryCast(ViewState("SortExpression"), String)
    If sortExpression IsNot Nothing Then
      ' Check if the same column is being sorted.
      ' Otherwise, the default value can be returned.
      If sortExpression = column Then
        Dim lastDirection = TryCast(ViewState("SortDirection"), String)
        If lastDirection IsNot Nothing _
          AndAlso lastDirection = "ASC" Then
          sortDirection = "DESC"
        End If
      End If
    End If
    ' Save new values in ViewState.
    ViewState("SortDirection") = sortDirection
    ViewState("SortExpression") = column
    Return sortDirection
End Function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top