简体   繁体   中英

sorting is not working on gridview in asp.net page

I use a gridview on my asp.net page. And write a code for sorting, but the problem is that the sorting is not working. Can you please tell me what i am doing mistake.

Code for bind the gridview

DataSet _ds = _fOrderWrapper.ExecuteDataSet();
   ViewState["FOrders"] = _rows;
   lblFinalisedCount.Text = _ds.Tables[0].Rows.Count.ToString();
   GridOpen.DataSource = _ds.Tables[0];
   ViewState["dt"] = _ds.Tables[0];
   ViewState["sort"] = "ASC";
    GridOpen.DataBind();
    UpdatePanel1.Update();

Sorting Event code :

try
    {
        DataTable dt1 = (DataTable)ViewState["dt"];
        if (dt1.Rows.Count > 0)
        {
            if (Convert.ToString(ViewState["sort"]) == "ASC")
            {
                dt1.DefaultView.Sort = e.SortExpression +" " + "DESC";
                ViewState["sort"] = "Desc";
            }
            else
            {
                dt1.DefaultView.Sort = e.SortExpression +" "+ "ASC";
                ViewState["sort"] = "ASC";
            }
            GridOpen.DataSource = dt1;
            GridOpen.DataBind();
            UpdatePanel1.Update();
        }
    }
    catch (Exception ex)
    {
    }

Your code might be hitting the sorting event code first, and then executing the regular data binding code second. The second data binding wipes out the effect of the first data binding. Try putting breakpoints in each location. When ASP.NET processes a request for an update panel, it runs the entire page life-cycle, not merely the event handler for the thing that triggered the update.

EDIT after further review:

Your code does this:

dt1.DefaultView.Sort = ...

Which changes the sorting for the default DataView associated with the DataTable.

But then it sets the data source for the gridview to the DataTable itself.

GridOpen.DataSource = dt1;

The Default DataView is not being used for data binding, I believe. (Been a while since I've done this, I might still be wrong).

I think you need to bind the GridView to the default DataView:

GridOpen.DataSource = dt1.DefaultView;

I think the reason the DefaultView is not automatically used when binding to the DataTable is that you would not otherwise have any way to bypass a DataView when binding to the data source.

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