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

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.

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=[...]");
    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.

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

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

Share

About the Author

João Melo
Web Developer
Portugal Portugal
No Biography provided

Comments and Discussions

 
GeneralSame thing but with GridView PinmemberUrs Enzler6-Aug-07 21:03 
I recently posted an article about a component to add a sort indicator image to the header of a GridView.
The sample application does more or less the same as yours but with a GridView.
 
May have a look at http://www.codeproject.com/useritems/GridViewSortIndicator.asp
 
-^-^-^-^-^-
no risk no funk

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
Web02 | 2.8.141030.1 | Last Updated 15 Jan 2008
Article Copyright 2007 by João Melo
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid