Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Simply adding sort icons to a DataGrid header

4.13/5 (6 votes)
15 Jan 2008CPOL1 min read 1   662  
Simply add sort (ASC+DESC) icons to a DataGrid header.

Screenshot - sorted_grid.jpg

Introduction

The default DataGrid is a very simple control that does not have a lot of manageability to it. So, if you want to customize it to your needs, you must code. Here is a simple way to add sort icons to the header.

Using the Code

After starting a new ASP.NET project, add the default DataGrid component to the ASPX page.

In order to populate the grid the first time you run the page, add the following code to Page_Load. I use ViewState to save the last field and the order sorted. Doing this will call the getData() method, which fills the grid with data, indicating a parameter for the default sort.

C#
if (!Page.IsPostBack)
{
    ViewState["sort"] = "id ASC";
    getData("id ASC");
}

The getData() method just queries the database - according to the sort parameter - and binds the results to the grid. In the end, I kill all objects created (old classic ASP habits...).

C#
private void getData(string sSort)
{
    OleDbConnection conn = 
      new OleDbConnection(@"Provider=VFPOLEDB.1;Data Source=[...]");
    conn.Open();
    OleDbCommand comm = new OleDbCommand();
    comm.Connection = conn;
    
    string strSQL = "SELECT id, date FROM table ORDER BY " + sSort;
    comm.CommandText = strSQL;
    
    dgOutput.DataSource = comm.ExecuteReader();
    dgOutput.DataBind();
    
    comm = null;
    conn.Close();
    conn = null;
}

Finally, you must code the SortCommand event for the DataGrid in order to display to the user which column is being sorted.

C#
private void dgOutput_SortCommand(object source, 
        System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{
    string[] s = ViewState["sort"].ToString().Split();    //load the last sort
    string sSort = e.SortExpression;
    
    //if the user is resorting the same column, change the order
    if (s[0] == sSort)
    {
        if (s[1] == "ASC")
            sSort += " DESC";
        else
            sSort += " ASC";
    }
    else
        sSort += " ASC";
    
    //find which column is being sorted to change its style
    int i = 0;
    foreach(DataGridColumn col in dgOutput.Columns)
    {
        if (col.SortExpression == e.SortExpression)
            dgOutput.Columns[i].HeaderStyle.CssClass = 
              "gridHeaderSort" + sSort.Substring(sSort.Length-4).Trim();
        else
            dgOutput.Columns[i].HeaderStyle.CssClass = "gridHeader";
        i++;
    }
    
    //get the sorted data
    getData(sSort);
    
    //save the new sort
    ViewState["sort"] = sSort;
}

The HTML code for the DataGrid should look like this:

ASP.NET
<asp:datagrid id="dgOutput" 
       runat="server" AllowSorting="True" 
       AutoGenerateColumns="False">
    <AlternatingItemStyle BackColor="#F8F8F8" />
    <ItemStyle ForeColor="Black" BackColor="#EEEEEE" />
    <HeaderStyle CssClass="gridHeader" />
    <Columns>
        <asp:BoundColumn DataField="id" 
                SortExpression="id" HeaderText="Id">
            <HeaderStyle CssClass="gridHeaderSortASC" />
            <ItemStyle HorizontalAlign="Right" />
        </asp:BoundColumn>
        <asp:BoundColumn DataField="date" 
                  SortExpression="date" HeaderText="Data">
            <ItemStyle HorizontalAlign="Center" />
        </asp:BoundColumn>
    </Columns>
</asp:datagrid>

Not least important are the CSS classes including the sort images to the header:

CSS
.gridHeader { font-weight:bold; color:white; background-color:#80a0a0; }
.gridHeader A { padding-right:15px; padding-left:3px; padding-bottom:0px; 
    color:#ffffff; padding-top:0px; text-decoration:none; }
.gridHeader A:hover { text-decoration: underline; }
.gridHeaderSortASC A 
  { background: url(../../../imagens/menus/sortdown.gif) no-repeat 95% 50%; }
.gridHeaderSortDESC A 
  { background: url(../../../imagens/menus/sortup.gif) no-repeat 95% 50%; }

Points of Interest

I used ViewState to keep track of the last order by clause. There are some other ways to do this: hidden field, session variable, etc.

History

  • Article created: 31 Jul 2007.
  • Source code uploaded: 26 Oct 2007.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)