buckshot buckshot - 19 days ago 6
C# Question

ASP.net Gridview not sorting

I have a gridview that I'd like to sort. I've read a few tutorials and copied most of my code directly from the MSDN page, but I can't get it to work. It compiles, but nothing happens when I click the grid column headers.

My HTML:

<asp:DataGrid runat="server" id="dgrMainGrid" CssClass="c_mainGrid"
AutoGenerateColumns="true" AllowSorting="true"
OnSorting="TaskGridView_Sorting" />


My Codebehind:

protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = Session["Grid"] as DataTable;

if (dt != null)
{
dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
dgrMainGrid.DataSource = dt;
dgrMainGrid.DataBind();
}
}

private string GetSortDirection(string column)
{
// By default, set the sort direction to ascending.
string sortDirection = "ASC";

// Retrieve the last column that was sorted.
string sortExpression = ViewState["SortExpression"] as string;

if (sortExpression != null)
{
// Check if the same column is being sorted.
// Otherwise, the default value can be returned.
if (sortExpression == column)
{
string lastDirection = ViewState["SortDirection"] as string;
if ((lastDirection != null) && (lastDirection == "ASC"))
{
sortDirection = "DESC";
}
}
}
return sortDirection;
}


I know the data table in my session variable works, because it's the source for my grid on page load, which works fine. One other thing, if it's important, this gridview resides in an update panel.

As I said, most of this is copied from the MSDN page, and I've been through it until I'm going code-blind. Can someone see my mistake? Thanks.

Answer

You are using a DataGrid, not a GridView. According to Microsoft, DataGrid does not have a OnSorting event, but an OnSortCommand. Either use that or switch to GridView (recommended)

<asp:DataGrid runat="server" OnSortCommand="dgrMainGrid_SortCommand" id="dgrMainGrid" CssClass="c_mainGrid" AutoGenerateColumns="true" AllowSorting="true" />

And in code behind

protected void dgrMainGrid_SortCommand(object source, DataGridSortCommandEventArgs e)
{
    DataTable dt = Session["Grid"] as DataTable;

    if (dt != null)
    {
        dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
        dgrMainGrid.DataSource = dt;
        dgrMainGrid.DataBind();
    }
}

And your GetSortDirection does not work as it should. See this example.

Comments