【问题标题】:ASP.net Gridview not sortingASP.net Gridview 不排序
【发布时间】:2017-03-28 13:39:08
【问题描述】:

我有一个要排序的网格视图。我已经阅读了一些教程并直接从 MSDN 页面复制了我的大部分代码,但我无法让它工作。它可以编译,但是当我单击网格列标题时没有任何反应。

我的 HTML:

<asp:DataGrid runat="server" id="dgrMainGrid" CssClass="c_mainGrid" 
AutoGenerateColumns="true" AllowSorting="true" 
OnSorting="TaskGridView_Sorting" />

我的代码隐藏:

protected void TaskGridView_Sorting(object sender, GridViewSortEventArgs e)
{
    //Retrieve the table from the session object.
    DataTable dt = Session["Grid"] as DataTable;

    if (dt != null)
    {
        dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
        dgrMainGrid.DataSource = dt;
        dgrMainGrid.DataBind();
    }
}

private string GetSortDirection(string column)
{
    // By default, set the sort direction to ascending.
    string sortDirection = "ASC";

    // Retrieve the last column that was sorted.
    string sortExpression = ViewState["SortExpression"] as string;

    if (sortExpression != null)
    {
        // Check if the same column is being sorted.
        // Otherwise, the default value can be returned.
        if (sortExpression == column)
        {
            string lastDirection = ViewState["SortDirection"] as string;
            if ((lastDirection != null) && (lastDirection == "ASC"))
            {
                sortDirection = "DESC";
            }
        }   
    }
    return sortDirection;
}

我知道我的会话变量中的数据表有效,因为它是我在页面加载时网格的来源,它工作正常。另一件事,如果它很重要,这个 gridview 驻留在更新面板中。

正如我所说,大部分内容都是从 MSDN 页面复制而来的,我一直通过它,直到我对代码视而不见。有人可以看到我的错误吗?谢谢。

【问题讨论】:

  • 您对 AutoPostBack 属性有什么价值?
  • 我什么都没有,只是试了真假,还是不行。

标签: c# asp.net sorting gridview


【解决方案1】:

您使用的是DataGrid,而不是GridView。根据Microsoft,DataGrid 没有OnSorting 事件,而是OnSortCommand。使用它或切换到 GridView(推荐)

<asp:DataGrid runat="server" OnSortCommand="dgrMainGrid_SortCommand" id="dgrMainGrid" CssClass="c_mainGrid" AutoGenerateColumns="true" AllowSorting="true" />

在后面的代码中

protected void dgrMainGrid_SortCommand(object source, DataGridSortCommandEventArgs e)
{
    DataTable dt = Session["Grid"] as DataTable;

    if (dt != null)
    {
        dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
        dgrMainGrid.DataSource = dt;
        dgrMainGrid.DataBind();
    }
}

您的GetSortDirection 无法正常工作。见this example

【讨论】:

  • VDWWD,我盯着它看了一个小时,没有发现我的网络元素有问题(我在故障排除时一直在尝试它们)。太感谢了。我现在正在精神上给你买啤酒。
猜你喜欢
  • 2016-07-31
  • 2011-09-02
  • 1970-01-01
  • 2023-03-12
  • 1970-01-01
  • 2018-04-11
  • 2011-01-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多