Sort Arrows on a ASP DataGrid

Here’s a little ditty I wrote to jam sort-order arrows onto the header cells of an ASP.NET DataGrid control. It’s pretty hacky, but basically iterates through the column collection until it finds a column with the specified ‘SortExpression’ property, and then creates an image control to stick into the header cell:

/// 
///		Sets an ascending or descending arrow in the correct column of the datagrid
/// 
///
The System.Web.UI.Page that the grid resides on
///
The datagrid on which you wish to set the arrow
///
The sort expression currently set on the grid
///
Is the sort currently ascending?

You should call it from the ItemDataBound event of the grid, and detect when the header row is created. In this example, orderBy (the current sort expression) and orderAscending (boolean) are page variables that I'm storing so that I can remember the current sorting:

private void grdCompany_ItemDataBound(object sender, DataGridItemEventArgs e)
{
  if( orderBy != null && orderBy.Length >= 0 )
  {
    if(e.Item.ItemType == ListItemType.Header)
      {
      FormUtils.SetSortImage( this, e.Item, orderBy, orderAscending );
    }
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *