Click here to Skip to main content
13,550,059 members
Click here to Skip to main content
Add your own
alternative version


38 bookmarked
Posted 31 Jul 2007
Licenced CPOL

Simply adding sort icons to a DataGrid header

, 15 Jan 2008
Rate this:
Please Sign up or sign in to vote.
Simply add sort (ASC+DESC) icons to a DataGrid header.

Screenshot - sorted_grid.jpg


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.

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...).

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

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

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";
            sSort += " ASC";
        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();
            dgOutput.Columns[i].HeaderStyle.CssClass = "gridHeader";
    //get the sorted data
    //save the new sort
    ViewState["sort"] = sSort;

The HTML code for the DataGrid should look like this:

<asp:datagrid id="dgOutput" 

       runat="server" AllowSorting="True" 

    <AlternatingItemStyle BackColor="#F8F8F8" />
    <ItemStyle ForeColor="Black" BackColor="#EEEEEE" />
    <HeaderStyle CssClass="gridHeader" />
        <asp:BoundColumn DataField="id" 

                SortExpression="id" HeaderText="Id">
            <HeaderStyle CssClass="gridHeaderSortASC" />
            <ItemStyle HorizontalAlign="Right" />
        <asp:BoundColumn DataField="date" 

                  SortExpression="date" HeaderText="Data">
            <ItemStyle HorizontalAlign="Center" />

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

.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.


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


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


About the Author

João Melo
Web Developer
Portugal Portugal
No Biography provided

You may also be interested in...

Comments and Discussions

Generalhelp me Pin
lequydien25-Oct-07 21:29
memberlequydien25-Oct-07 21:29 
can you post source sample ?
i stuck in Css class , it can not get image
AnswerRe: help me Pin
João Melo25-Oct-07 23:23
memberJoão Melo25-Oct-07 23:23 
GeneralRe: help me Pin
lequydien28-Oct-07 14:38
memberlequydien28-Oct-07 14:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web03-2016 | 2.8.180515.1 | Last Updated 15 Jan 2008
Article Copyright 2007 by João Melo
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid