Geeks With Blogs
Justin Gardner .NET, T-SQL and Reporting Services Developer
Seeing as I wrestled with this topic for the better part of a day, I'll post the process here for posterity and for the off chance someone finds it useful.

Pardon my lack of proper terminology here. I'd rather get the concept down quickly than look everything up.

In your ASPX page, your GridView control needs an OnSorting setting.

<asp:GridView ID="SomeName" runat="server" AllowSorting="true" AutoGenerateColumns="false" OnSorting="gvSorting">

Now, in your code behind, you need to have a code block for the sorting command. Here's what I used.

Protected Sub gvSorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
        Dim dt As DataTable = ViewState.Item("dt")    ' My datatable is being pulled in from ViewState
        Dim dv As DataView = dt.DefaultView               ' Copy the default view of your DataTable to the DataView
        Dim sd As String                                                    ' e.SortDirection contains something like Ascending {0} instead of asc
        If e.SortDirection.ToString.Contains("asc") Then
            sd = "asc"
        ElseIf e.SortDirection.ToString.Contains("desc") Then
            sd = "desc"
        Else
            sd = ""asc"                                                              ' Use a default sort direction to avoid potential null reference exceptions
        End If

        dv.Sort = e.SortExpression + " " + sd                       ' e.SortExpression contains the column name
        dt = dv.ToTable                                                         ' Send the sorted table back to dt, our DataTable
        gvResults.DataSource = dt                                         ' Reset the GridView contol's DataSource property
        gvResults.DataBind()                                                 ' Re-bind the GridView to the DataSource
End Sub

Now, the above worked in my case and will hopefully get you going as well. I'd recommend wrapping this in a Try Catch block to catch exceptions. Also, I'd make sure to check the ViewState object is not null as well. Something along the lines of this:

Protected Sub gvSorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
        Dim dt As DataTable = ViewState.Item("dt")    ' My datatable is being pulled in from ViewState
        Dim dv As DataView = dt.DefaultView               ' Copy the default view of your DataTable to the DataView
        Dim sd As String                                                    ' e.SortDirection contains something like Ascending {0} instead of asc

        If Not dt Is Nothing Or Not dt Is "" Then
            If e.SortDirection.ToString.Contains("asc") Then
                sd = "asc"
            ElseIf e.SortDirection.ToString.Contains("desc") Then
                sd = "desc"
            Else
                sd = "asc"
            End If

            Try
                dv.Sort = e.SortExpression + " " + sd 'e.SortDirection.ToString
                dt = dv.ToTable
                gvResults.DataSource = dt
                gvResults.DataBind()
            Catch ex As Exception
                ' Whatever you want to do here for exception management
            End Try

        End If
End Sub


That's all I have. Posted on Thursday, July 2, 2009 9:52 AM ASP.NET , VB.NET | Back to top


Comments on this post: Sorting A Gridview That's Bound To A DataTable

# re: Sorting A Gridview That's Bound To A DataTable
Requesting Gravatar...
Superb code Justin..!!! My compliments for you...

I made some changes made it work with my GridView in asp.net 2.0 with C#

Here it is I am posting for your and the reader's reference.

step 1:Populate the ViewState with the datasource of the gridview in the !Page.IsPostback event .

Step 2: In Gridview set AllowSorting="true"

Step: 3: Add the sortexpression="ColumnName"

Step 4: Handle the Onsorting event of the grid on the server side as follows:

protected void grdRoomTypeMaster_OnSorting(object sender, GridViewSortEventArgs e)
{
DataTable dtGridData = ViewState["grdDataSource"] as DataTable;
DataView dvGridDataView = dtGridData.DefaultView;
string strSortOrder = "";
if (ViewState["SortOrder"]==null)
{
ViewState["SortOrder"] = "asc";
}
if (ViewState["SortOrder"].ToString() == "asc")
{
ViewState["SortOrder"] = "desc";
strSortOrder = "desc";
}
else if (ViewState["SortOrder"].ToString() == "desc")
{
ViewState["SortOrder"] = "asc";
strSortOrder = "asc";
}
dvGridDataView.Sort = e.SortExpression + " " + strSortOrder;
dtGridData = dvGridDataView.ToTable();

grdRoomTypeMaster.DataSource = dtGridData;
grdRoomTypeMaster.DataBind();
}
Left by Balaji Birajdar on Feb 04, 2010 6:36 AM

# re: Sorting A Gridview That's Bound To A DataTable
Requesting Gravatar...
Thanks Justin..
Left by Balaji Birajdar on Apr 16, 2010 2:58 AM

Your comment:
 (will show your gravatar)


Copyright © Justin | Powered by: GeeksWithBlogs.net