0
votes

The default sorting order on the gridview control is ascending first, then descending. Now below I have code to change that around. So far so good. But when I click on another column again, it sets the sort direction to ascending again. It alternates between descending and ascending on every click, no matter which column. Now what I really want is for the first click on any column to be descending, and if I click any column for the second time(second time meaning consecutively), it should be ascending. Example: I have 2 columns, one is salary and the other is age. Now I click on salary, and the first sorting direction is descending, not the default ascending(that's what the code does). Now when I click on age, it switches the sorting direction to ascending, I want it to stay the same when I change to another column, BUT should I click on salary again for the second time, it should switch to ascending(cause descending was the first click). Any suggestions?

My code:

public SortDirection GridViewSortDirection
{
    get
    {
        if (ViewState["sortDirection"] == null) 
            ViewState["sortDirection"] = SortDirection.Ascending;
        return (SortDirection)ViewState["sortDirection"];
    }
    set
    {
        ViewState["sortDirection"] = value; 
    }
}
protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e)
{
    if (ViewState["sortDirection"] == null)
    {
        e.SortDirection = SortDirection.Descending;
    }
    else if (GridViewSortDirection == SortDirection.Ascending)
    {
        e.SortDirection = SortDirection.Descending;
    }
    else if (GridViewSortDirection == SortDirection.Descending)
    {
        e.SortDirection = SortDirection.Ascending;
    }

    GridViewSortDirection = e.SortDirection;
}
1

1 Answers

0
votes

Try checking to determine whether the SortExpression has changed from the previously set SortExpression and if so default the SortDirection to Descending.

protected void GridView1_OnSorting(object sender, GridViewSortEventArgs e)
{
    if (e.SortExpression != GridView1.SortExpression)
    {
        e.SortDirection = SortDirection.Descending;
        GridViewSortDirection = e.SortDirection;
    }
    else if (GridViewSortDirection == SortDirection.Ascending)
    {
        e.SortDirection = SortDirection.Descending;
    }
    else if (GridViewSortDirection == SortDirection.Descending)
    {
        e.SortDirection = SortDirection.Ascending;
    }

    GridViewSortDirection = e.SortDirection;
}