All posts tagged 'gridview-aspnet'

GridView Sort Column Arrow Performance

by JBrooks 23. February 2009 16:11

I see code like the following a lot:

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
     if (e.Row.RowType == DataControlRowType.Header)
            if (String.Empty != this.GridView1.SortExpression)  
                     AddSortImage(e.Row);             
           
}

The problem with this is that it fires for each row in the GridView slowing performance.  A better way is the following which only fires once per GridView binding:

protected void GridView1_DataBound(object sender, EventArgs e)
{
     if
(String.Empty != this.GridView1.SortExpression) 
            AddSortImage(GridView1.HeaderRow);
}

The supporting methods are:

void AddSortImage(GridViewRow headerRow) 

     int
iCol = GetSortColumnIndex();
     if
(-1 == iCol) 
           return

     // Create the sorting image based on the sort direction.

     Image sortImage = new Image();
     if
(SortDirection.Ascending == this.GridView1.SortDirection) 

{             sortImage.ImageUrl = @"~\Images\BlackDownArrow.gif";
               sortImage.AlternateText = "Ascending Order";
}
     else 

{
             sortImage.ImageUrl = @"~\Images\BlackUpArrow.gif";

             sortImage.AlternateText = "Descending Order";

}
      // Add the image to the appropriate header cell.
        headerRow.Cells[iCol].Controls.Add(new LiteralControl(" "));
        headerRow.Cells[iCol].Controls.Add(sortImage);
}

public int GetSortColumnIndex()
{
      // Iterate through the Columns collection to determine the index
      // of the column being sorted. 
      foreach (DataControlField field in GridView1.Columns)
       {
             if (field.SortExpression == this.GridView1.SortExpression)
               {
                  return this.GridView1.Columns.IndexOf(field);
                }
         }
      return -1;
}

Tags:

ASP.Net | GridView