Click here to Skip to main content
Click here to Skip to main content

Simply adding sort icons to a DataGrid header

, 15 Jan 2008 CPOL
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

Comments and Discussions

Generalhelp me Pinmemberlequydien25-Oct-07 22:29 
AnswerRe: help me PinmemberJoão Melo26-Oct-07 0:23 
I posted the source sample.
Tell me if your problem persists.
GeneralRe: help me Pinmemberlequydien28-Oct-07 15:38 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150326.1 | Last Updated 15 Jan 2008
Article Copyright 2007 by João Melo
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid