【问题标题】:Sorting Data gridview by clicking header in asp.net通过单击 asp.net 中的标题对数据网格视图进行排序
【发布时间】:2013-03-24 06:57:50
【问题描述】:

请通过单击 asp.net 中的标题帮助我在网格视图中对数据进行排序。我使用 linq 将数据绑定到 gridview。请帮帮我。

【问题讨论】:

  • 问题标题上的小谷歌会回答你。 Google 在(0.29 秒)内返回了大约 192,000 个结果.. :)

标签: asp.net linq sorting gridview


【解决方案1】:

你可以很容易地做到这一点。

假设您有一个 GridView,您可以在服务器端为其分配数据源。

您可以使用GridView_Sorting 事件,如下所示:

首先,将当前应用的排序保存在某处。因为,您需要知道是否必须按升序或降序排序。如下所示。

public SortDirection CurrentSortDirection
{
    get
    {
        if (ViewState["sortDirection"] == null)
            ViewState["sortDirection"] = SortDirection.Ascending;

        return (SortDirection) ViewState["sortDirection"];                
    }
    set { ViewState["sortDirection"] = value; } 
}

然后在 GridView 的sorting 事件中使用这个属性:

protected void GridView_Sorting(object sender, GridViewSortEventArgs e)
{
   if (CurrentSortDirection== SortDirection.Ascending)
   {
      CurrentSortDirection = SortDirection.Descending;
      var myDataSource = GetDataThroughLinq()
                         .OrderByDescending(s=>s.Id)
                         .ToList();
      GridView1.DataSource = myDataSource;
      GridView1.DataBind();
   }
   else
   {
      CurrentSortDirection = SortDirection.Ascending;
      var myDataSource = GetDataThroughLinq()
                         .OrderBy(s=>s.Id)
                         .ToList();
      GridView1.DataSource = myDataSource;
      GridView1.DataBind();
   }   
}

【讨论】:

    【解决方案2】:

    您可以直接为gridview选择一个数据源,它在gridview任务中的自动格式下方,选择datasouce后提供了更多选项,它也包括排序,分页和选择,通过单击每个标题,您将获得数据按照它排序

    【讨论】:

      【解决方案3】:

      试试这个排序.....

      protected void RadgvData_SortCommand(object sender, GridSortCommandEventArgs e)
          {
              GridTableView tableView = e.Item.OwnerTableView;
              e.Canceled = true;
              GridSortExpression expression = new GridSortExpression();
              expression.FieldName = e.SortExpression;
              if (tableView.SortExpressions.Count == 0 || tableView.SortExpressions[0].FieldName != e.SortExpression)
              {
                  expression.SortOrder = GridSortOrder.Descending;
              }
              else if (tableView.SortExpressions[0].SortOrder == GridSortOrder.Descending)
              {
                  expression.SortOrder = GridSortOrder.Ascending;
              }
              else if (tableView.SortExpressions[0].SortOrder == GridSortOrder.Ascending)
              {
                  expression.SortOrder = GridSortOrder.Descending;
              }
      
              tableView.SortExpressions.AddSortExpression(expression);
              RadgvData.Rebind();
      
          }
      

      【讨论】:

        猜你喜欢
        • 2021-07-30
        • 2018-02-23
        • 2016-10-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多