GridView sorting


I create a GridView programatically and bind it to a DataView. Works fine until it comes to sorting. Clicking those columns that i have set to be sortable makes
my event handler fire only every second time. Sorting becomes correct, but it always needs two clicks to be correct.

I create my GridView like this:

GridView gw = new GridView();
gw.AutoGenerateColumns = false;
gw.GridLines = GridLines.Horizontal;
gw.AllowSorting = true;
gw.Sorting += new GridViewSortEventHandler(Sorting);


The event handler:

    public void Sorting(object sender, GridViewSortEventArgs e)
    {
        ViewState["sortExpression"] = e.SortExpression;

        if (GridViewSortDirection == SortDirection.Ascending)
            GridViewSortDirection = SortDirection.Descending;
        else
            GridViewSortDirection = SortDirection.Ascending;

        BuildRanking(ViewState["sortExpression"].ToString(), ViewState["sortDirection"].ToString());
    }

BuildRanking sorts the dataview and binds it to the gridview.

Any help out there?

oslonetAsked:
Who is Participating?
 
GranModConnect With a Mentor Commented:
PAQed with points refunded (500)

GranMod
Community Support Moderator
0
 
SystemExpertCommented:
Hi ,

You require to save the Order of the column

that is ASC or DESC
==========================
dvTable.Sort = sortExp + " ASC";
                        
if (ViewState[SortOrder]==null)
{
      //If no any previous order then set default ASC
      ViewState[SortOrder]="ASC";
}
      if(ViewState[SortOrder].ToString () == "ASC" || ViewState[SortOrder].ToString () =="")
      {      
            dvTable.Sort = sortExp + " ASC";
            ViewState[SortOrder] = "DESC" ; //store  it for Next Time
      }
                else
      {
            dvTable.Sort = sortExp + " DESC";
            ViewState[SortOrder] = "ASC" ; // store it for Next Time
      }
                        
      dgApp.DataSource=dvTable;
      dgApp.DataBind();
==========================
Thanks
0
 
oslonetAuthor Commented:
It is saved... Didn't post that part of the code....

    public SortDirection GridViewSortDirection
    {
        get
        {
            if (ViewState["sortDirection"] == null)
                ViewState["sortDirection"] = SortDirection.Descending;

            return (SortDirection)ViewState["sortDirection"];
        }
        set { ViewState["sortDirection"] = value; }
    }
0
 
oslonetAuthor Commented:
Found the solution. Needed to rebind in my sorting handler.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.