开发者

how to sort Gridview rows by a unbound Template column

开发者 https://www.devze.com 2022-12-23 22:25 出处:网络
i want开发者_开发技巧 to sort my Gridview rows by a template column that is not bound to any database field. This template coulmn just has a label whose text i set in code depending on a value in a di

i want开发者_开发技巧 to sort my Gridview rows by a template column that is not bound to any database field. This template coulmn just has a label whose text i set in code depending on a value in a different column that is databound. So am stuck on how to set its sortExpression since its not linked to an column.


Your desired behaviour is possible. Here is what you need to do:

1) Subscribe to the Sorting Event of the GridView.
2) Add a SortExpression to your create column, like "MyOwnSortExpression". 2) In the eventhandler, you have access to the SortExpression via the EventArgs. e.SortExpression 3) Create a method that performs the DataBinding on the GridView. This method has 2 parameters. The first one is the name of the column that should be sorted, and the second is the Sortdirection. (would be nice to toggle the sortdirection after clicking the same column twice) 4) Add code-switch that performs manually sorting only on the desired Columsn.

Example:

protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
  if(e.SortExpression == MyOwnSortExpression)
  {
     UpdateDataBinding(e.SortExpression, e.SortDirection);   
     e.Cancel = true;
     return;
  }
}

protected void UpdateDataBinding(String sortexpression, SortDirection direction)
{
  switch(sortExpression)
  {
    case "MyOwnSortExpression":
      var myData = GetYouSpecificDataFromDB();
      if(direction == SortDirection.Ascending)
      {
       var = var.OrderBy(x => string.format("jkalsd{0}", x.TheSpecifiedDBColumn)) // or any desired linq expression);
      }
      else
      {
       var = var.OrderByDescending(x => string.format("jkalsd{0}", x.TheSpecifiedDBColumn)) // or any desired linq expression);
      }
      this.gv.DataSource = var.ToList();
      this.gv.DataBind();
      break;
  }
}

You can add caching for the sortdirection and the sort column to enable a toggling mechanism.

Your solution might vary, based on the kind of databinding you are doing (Linq-to-Sql, ObjectDataSource, ...)

This link http://blogs.sftsrc.com/stuart/archive/2009/02/19/130.aspx also provides a nice class. Works best if you can create a Wrapperclass, containing all values that are going to be displayed. The solution I suggested does not need a wrapper class, but it lacks in flexiblity.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号