Refactor Code

  • Gravatar
    Sort Image for bound columns in GridView

    by r4ramki on 5/15/2008 12:34:15 PM
  • 1. Call grdGrid_Sorting onsorting event of GridView 2. set the variable GridViewSortDirection to "Asc" or "Desc" based on the sort direction. 2. call GridViewSortImages from the sorting method. This is a generic code and should work without any modifications.
  • protected void grdGrid_Sorting(object sender, GridViewSortEventArgs e)
    {
    GridViewSortImages(grdGrid, e);
    }

    protected void GridViewSortImages(GridView grdView, GridViewSortEventArgs e)
    {
    foreach (TableCell cell in grdView.HeaderRow.Cells)
    {
    if (cell.HasControls())
    {

    LinkButton button = cell.Controls[0] as LinkButton;

    if (button != null)
    {

    Image image = new Image();

    image.ImageUrl = "images/spacer.gif";

    if (e.SortExpression == button.CommandArgument)
    {

    if (GridViewSortDirection == "ASC")

    image.ImageUrl = "images/downa.gif";

    else

    image.ImageUrl = "images/upa.gif";

    }
    cell.Controls.Add(image);
    }

    }

    }
    }
  • Refactor it!
  • Gravatar
    You can refactor the code of sorting out to a much simpler method that can be called during the binding operation of the DataGrid control. Also, you don't need to create the Image again and again inside the sorting event. You only need to change the image url and that's it.
    by azamsharp on 5/15/2008 9:09:29 PM

  • protected string ToggleDataGridSortDirection()
    {
    if(GridViewSortDirection == "ASC")
    return "images/downa.gif";

    return "images/upa.gif";
    }
  • Gravatar
    its working.great
    by fareedkhan on 6/2/2008 5:51:32 AM
Please log in to refactor the code! Login