Saturday, March 26, 2011

Simple Dynamic Sorting Headers for GridView using indication arrows

Simple Dynamic Sorting Headers for GridView using indication arrows

A simple centralized way to make a nice flipping indicator (arrow) of which way you are sorting on a GridView

When sorting with gridviews, it is nice to have an indicator of which direction you are sorting on which field like the use at Yahoo! Autos. To copy this idea, I simply made 3 Css classes 'sort', which is a base class with no backgorund image, 'up' which has an up arrow, and 'down' which has a down arrow in it. I made sure to put the backgorund image in just once, and push the text away so it can show through. Also, since these will be applied to the Header element of the GridView, you have to make sure you declase '.class a':
.up a, .down a, .sort a { display:block; padding:0 4px 0 15px; }
.up a, .down a { color:#8F5F00; }
.sort a:hover { background:#ffcc66; }
.up a { background:url(../images/up.gif) left no-repeat; }
.up a:hover { background:url(../images/up.gif) left no-repeat #ffcc66; }
.down a { background:url(../images/down.gif) left no-repeat }
.down a:hover { background:url(../images/down.gif) left no-repeat #ffcc66; }

Now, I made a function in a helper Class that will take in the same arguments that a GridView Sorting event throws, that way the transition will be easy.
// This is used to flip the sorting arrow up/down
// Base Css class is 'sort', the Ascending Css Class is 'up' and Descending is 'down'
public static void GVSort(object sender, GridViewSortEventArgs e)
{ // call on sort and sets the sorted field to the proper Css Class, while setting all others to the base class
  string BASE = "sort";
  string UP = "up";
  string DOWN = "down";
  GridView g = (GridView)sender;
  for (int i = 0; i < g.Columns.Count; i++)
  {
    var c = g.Columns[i];
    c.HeaderStyle.CssClass = c.HeaderStyle.CssClass.Replace(UP, BASE).Replace(DOWN, BASE);
    if (c.SortExpression.Equals(e.SortExpression))
    {
      c.HeaderStyle.CssClass =
        e.SortDirection.Equals(System.Web.UI.WebControls.SortDirection.Ascending) ?
          c.HeaderStyle.CssClass.Replace(BASE, UP).Replace(DOWN, UP) :
          c.HeaderStyle.CssClass.Replace(BASE, DOWN).Replace(UP, DOWN);
    }
  }
}

Now say I had this in a class utils.cs I would just call it one the GridView Sorting event:
protected void gv_Sorting(object sender, GridViewSortEventArgs e)
{
  sao.GVSort(sender, e);
}

And there you have it! You can call that from every Gridview in your application that you want to look similar - code only once! 
 

No comments:

Post a Comment