Click here to Skip to main content
14,980,986 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Guys,

I have a grid that binds the data at runtime...

Dim myCommand = New SqlCommand(strSql, myConnection)
Dim dr As SqlDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)

gvLiveCourses.Visible = True
gvLiveCourses.DataSourceID = ""
gvLiveCourses.DataSource = dr

Next is the OnSort event and function. Actually I just copied it from other forums.

Sub gvLiveCourses_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) 'Handles gvLiveCourses.Sorting
    Dim m_DataTable As DataTable = TryCast(gvLiveCourses.DataSource, DataTable)
    If m_DataTable IsNot Nothing Then
        Dim m_DataView As New DataView(m_DataTable)
        m_DataView.Sort = e.SortExpression + " " & ConvertSortDirectionToSql(e.SortDirection)
        gvLiveCourses.DataSource = m_DataView
    End If
End Sub
Function ConvertSortDirectionToSql(ByVal sortDirection As SortDirection)
    Dim newSortDirection As String = String.Empty
    Select Case (sortDirection)
        Case sortDirection.Ascending
            newSortDirection = "ASC"
        Case sortDirection.Descending
            newSortDirection = "DESC"
    End Select
    Return newSortDirection
End Function

Now, when I click on the gridview columns it doesn't sort. And when I traced it using breakpoints, I found out that the m_DataTable is empty. But how come this becomes empty since the grid displays the data. I don't get it.

Please let me know on how to correct this code. I am using sqldatareader most of my applications, and I need to add sorting feature on every gridview. There's no problem in the gridview, only the sort feature that has to be added.

I hope you could give me a sample on sorting the gridview using sqldatareader that binds the data at runtime.


Updated 6-Oct-10 11:05am


this sounds like a postback-issue. You have to make sure that
your data is retrieved during a postback somehow. Easiest way would
be to rebind your datasource on every postback. But that may not be an
option. There are other possibilities.

Find them by binging for "gridview postback datasource sorting" or similiar. There are lots of discussions about that topic out there.

Good luck

GridView always render (output) as html table format.
GridView is just an container for hoding rows and columns.
The data you viewing on web page is the rendered data table not the GridView or Datatable.

Now where you want to apply sorting, on data rite. So you need data for that, rebind the datatable from DB table or store your datatable in viewstate or in session then retrive, do sorting again bind to GridView DataSource.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900