sorting is not working on gridview in asp.net page

若如初见. 提交于 2019-12-13 02:25:43

问题


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)
    {
    }

回答1:


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.



来源:https://stackoverflow.com/questions/34329541/sorting-is-not-working-on-gridview-in-asp-net-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!