2

它的阿伦。这次我在 ASP.Net 中有一个排序问题。对于第一次单击,降序工作正常,但在第二次单击时,不会再次进行升序。它仍然按降序排列。我正在使用 Tableadapter 来显示 gridview 内容。请查看代码并纠正我错过的地方。

    protected void gv1_Sorting(object sender, GridViewSortEventArgs e)
    {
        string sdir = e.SortDirection == SortDirection.Ascending ? "DESC" : "ASC";
        DataView dv = new DataView(ds2.AllocationPending(ClientLoggedIn.Text));
        dv.Sort = e.SortExpression + " " + sdir;
        gv1.DataSource = dv;
        gv1.DataBind();
    }

另请解释 - 有没有其他方法可以在没有 Dataview 的情况下应用排序。

谢谢你 。

4

2 回答 2

2

我已经找到了这个问题的解决方案。原因是 e.SortDirection 总是返回 Ascending。所以我需要将 e.SortDirection 存储在 ViewState 中,并使用该值对数据视图进行排序。更新的编码如下:

    protected void gv1_Sorting(object sender, GridViewSortEventArgs e)
    {
        string SortDirection = "DESC";
        if (ViewState["SortExpression"] != null)
        {
            if (ViewState["SortExpression"].ToString() == e.SortExpression)
            {
                ViewState["SortExpression"] = null;
                SortDirection = "ASC";
            }
            else
            {
                ViewState["SortExpression"] = e.SortExpression;
            }
        }
        else
        {
            ViewState["SortExpression"] = e.SortExpression;
        }

        DataView dv = new DataView(ds2.AllocationPending(ClientLoggedIn.Text));
        dv.Sort = e.SortExpression + " " + SortDirection;
        gv1.DataSource = dv;
        gv1.DataBind();
    }
于 2013-05-08T06:18:03.977 回答
1
 protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {      
        DataTable dtSortTable = GridView1.DataSource as DataTable;

        if (dtSortTable != null)
        {
            DataView dvSortedView = new DataView(dtSortTable);

            dvSortedView.Sort = e.SortExpression + "" + getSortDirectionString(e.SortDirection);

            GridView1.DataSource = dvSortedView;
            GridView1.DataBind();
        }
    }

private string getSortDirectionString(SortDirection sortDirection)
    {
        string newSortDirection = String.Empty;
        if(sortDirection== SortDirection.Ascending)
        {
            newSortDirection = "DESC";
        }
        else
        {
            newSortDirection = "ASC";
        }
        return newSortDirection;
}

尝试使用此代码对 gridview 进行排序

于 2013-05-07T10:08:31.590 回答