简体   繁体   中英

Sorting works only once

I have GridView with sorting, it works quite well, but it works only once, and yes this is not a duplicate I found lot of question, but it doesn't help me. Please what is wrong that it sort only once (like a direction is not changing) ?

        ViewState["sort"] = "ASC" --> is declared in PageLoad

        protected void grid_sort(object sender, GridViewSortEventArgs e) 
        {
            DataView sorting = new DataView(data); //data is global DataTable

            if (ViewState["sort"].ToString() == "ASC")
                ViewState["sort"] = "DESC";
            else
                ViewState["sort"] = "ASC";

            sorting.Sort = e.SortExpression + " " + ViewState["sort"];
            data = sorting.ToTable();
            GridView1.DataSource = data;
            GridView1.DataBind();
        }

All objects are disposed at the end of the page's lifecycle, so when it's rendered as HTML and sent to the client. So you can't use the field string direction = "ASC" to store the sort direction. That will be initialized to "ASC" on every postback.

Instead you have to use a different way, for example:

  • Session
  • ViewState
  • HiddenField

ASP.NET State Management Overview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM