Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
        }
like image 487
tomsk Avatar asked Mar 23 '26 21:03

tomsk


1 Answers

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

like image 187
Tim Schmelter Avatar answered Mar 26 '26 13:03

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!