Hi,

I'm trying to allow sorting my gridview writing in the code behind page. My code for Bind the GridView is like this:
   Private Sub BindMyGridView()
        Dim DatabaseConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("MyServer").ConnectionString)
        Dim adapter As SqlDataAdapter = New SqlDataAdapter
        Dim selectSQL As String = "SELECT * FROM Clients WHERE id = @id"
        Dim selectCMD As New SqlCommand(selectSQL, DatabaseConnection)
        Dim id As Integer = firstGridView.SelectedValue

        selectCMD.Parameters.Add(New SqlParameter("@id ", SqlDbType.Int))
        selectCMD.Parameters("@id ").Value = id

        adapter.SelectCommand = selectCMD

        Dim dTable As DataTable = New DataTable
        adapter.Fill(dTable)

        MyGridView.DataSource = dTable
        MyGridView.DataBind()
    End Sub

And my code for sorting is like this:

Private Function SortDirectionSQL(ByVal direction As SortDirection) As String
        Dim directionSQL As String = ""
        Select Case direction
            Case SortDirection.Ascending
                directionSQL = "ASC"
            Case SortDirection.Descending
                directionSQL = "DESC"
        End Select
        Return directionSQL
    End Function

    Protected Sub MyGridView _OnSorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs)
        Dim dTable As DataTable = MyGridView.DataSource
        If dTable.Rows.Count > 0 Then
            Dim dView As New DataView(dTable)
            dView.Sort = e.SortExpression + " " + SortDirectionSQL(e.SortDirection)
            MyGridView.DataSource = dView
            BindMyGridView ()
        End If
    End Sub

However, the proble I'm having is in the line:

dTable.Rows.Count > 0

and this is happening becaus emy DataSource is always nothing.

Does anyone have ideas about how to solve this problem?

Thanks in advance.

Ana

Dani AI

Generated

GridView sorting fails here for a common reason: the GridView does not persist its DataSource across postbacks, so the Sorting event runs without the original DataTable unless that data is preserved or reloaded. and pointed toward Session/ViewState storage — that is the right direction, but a few practical rules make the pattern reliable and performant.

Persist the bound data only when appropriate. For very small result sets, storing the DataTable in ViewState is simplest; for larger sets use Session or re-query the database with an ORDER BY. Track the current sort expression and direction in ViewState (or another server store) and toggle the direction yourself instead of relying on the SortDirection supplied by the event. On Sorting: retrieve the stored DataTable, create a DataView (or apply server-side ORDER BY), set the sort expression plus direction, then rebind the GridView.

Quick checklist of common pitfalls to verify:

  • AllowSorting is enabled and BoundField/TemplateField SortExpression values are set.
  • The Sorting handler is actually wired (OnSorting matches the code-behind signature).
  • Page_Load does not rebind the GridView unconditionally (wrap initial bind in If Not IsPostBack).
  • Avoid storing large DataTables in ViewState (page bloat); prefer Session or server sorting for scalability.
  • Watch SQL parameter names carefully (extra whitespace in parameter names will break parameter binding).

For performance and scalability, prefer server-side sorting (SQL ORDER BY) when datasets are nontrivial. Official references: GridView.Sorting event and DataView.Sort property. @AnaD reported a working solution and the above notes explain why storing/retrieving the DataTable (or using server-side sorting) fixes the null-DataSource problem.

Recommended Answers

All 7 Replies

You cannot get the DataSource from GridView. You should store it in the Session or again fill it from database, sort it and then bind to the GridView again.

For small amount of data you can use viewstate. Better to use a datatable to bind so that for next time no need to go to the database. You can sort on datatable & rebind to Gridview.

I changed my code and now I'm able to retrieve the DataSource. Now what I have is:

Protected Sub MyGridView_OnSorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs)
Dim dTable As DataTable = MyGridViewDataSource()
If dTable.Rows.Count > 0 Then
Dim dView As New DataView(dTable)
dView.Sort = e.SortExpression + " " + SortDirectionSQL(e.SortDirection)
MyGridView.DataSource = dView
MyGridView.DataBind()
End If
End Sub

But even now the sorting is not working. It simply doesn't do anything. Does anyone have any ideas about what is happening?

Thanks a lot!

Put a break point in this event and check the execution control goes inside dTable.Rows.Count > 0 condition.

Hi Ana,
Ignore my last post. Sorry, I didn't refresh to see your last post.

No problem! Thanks anyway :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.