Click here to Skip to main content
13,346,397 members (64,050 online)
Click here to Skip to main content
Add your own
alternative version


45 bookmarked
Posted 13 Aug 2004

Optimized ASP.NET DataGrid Sorting

, 13 Aug 2004
Rate this:
Please Sign up or sign in to vote.
Minimize viewsate and database access to achieve optimized DataGrid sorting.


Typical ASP.NET DataGrid sorting concerns database access and saving data in viewstate. So, minimizing database access times and the size of viewstate would be the key to achieve optimal DataGrid sorting solution. To minimize database access, it would be a good solution to keep data source in cache such that its time and memory will be balanced. To minimize viewstate, we can turn off the viewstate. However, if the viewstate is disabled, the built-in sorting functionality would get lost and thus the beauty of DataGrid sorting would disappear since we may have to provide extra buttons. This article introduces a way to overcome the deficiency above to achieve optimal DataGrid sorting, and also a way to minimize page viewsate while still keeping its functionality.

Non-display ASP.NET Button

For ASP.NET Button, it has two important properties: Enabled and Visible. Often, another style property is overlooked. That is, Display. If Display is set to none, the Button would disappear when it is browsed. But note that it still exists in DHTML object model and it functions like a visible button. We can use this nice feature to disable DataGrid viewstate. And then use JavaScript to transfer a click event to a non-display button to trigger page postback. In the event handler of this button at server side, we can do things as in DataGrid item command event handler.


To demonstrate this idea, put the following piece of code in HTML page. Note that DataGrid viewstate has been turned off. A non-display button has been added in.

<asp:datagrid id="dgTest" Runat="server" Width="90%" 

          EnableViewState="False" ShowHeader="True"

          AutoGenerateColumns="False" GridLines="Horizontal" 

    <HeaderStyle Wrap="False" Font-Bold="True" BackColor="#3300cc" 

    <AlternatingItemStyle BackColor="LawnGreen"></AlternatingItemStyle>
      <asp:BoundColumn HeaderText="Last Name" DataField="LastName" 

      <asp:BoundColumn HeaderText="First Name" DataField="FirstName" 

      <asp:BoundColumn HeaderText="Address" DataField="Address" 

      <asp:BoundColumn HeaderText="City" DataField="city" 

      <asp:BoundColumn HeaderText="Region" DataField="Region" 

      <asp:BoundColumn HeaderText="PostalCode" DataField="PostalCode" 

      <asp:BoundColumn HeaderText="Country" DataField="Country" 

          View Detail
        <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
          <asp:LinkButton ID="lnkSelect" Runat="server" 

        <ItemStyle HorizontalAlign="Center"></ItemStyle>
<asp:Button ID="SortButton" style="DISPLAY:none" Runat="server" 


To transfer an event click to non-display button, modify head text and add some JavaScript as follows:

private void SetHeadText(SORT_ORDER order)
    string headtext = "<a href='#' onclick='javascript:document" + 
            ".getElementById(\"{0}\").click();'> Address</a>";
    if(order == SORT_ORDER.DESC)
        this.dgTest.Columns[this.Col_Address].HeaderText = 
        this.dgTest.Columns[this.Col_Address].HeaderText = 

In button event handler, add the following code. Sort order has been saved in page viewstate.

private void SortButton_Click(object sender, System.EventArgs e)
    if(order == SORT_ORDER.ASC)

Next is bind data. SetHeadText must be called before calling DataGrid's DataBind function.

private void BindData(SORT_ORDER order)
    DataView dv = this.GetDataSource().DefaultView;

    if(order == SORT_ORDER.ASC)
        this.SetHeadText(SORT_ORDER.DESC);//for future
        this.ViewState[SORTORDER] = SORT_ORDER.ASC; //for current
        dv.Sort = "Address ASC";
        this.SortLabel.Text = "Current sorting order is ascending";
        this.SetHeadText(SORT_ORDER.ASC);//for future
        this.ViewState[SORTORDER] = SORT_ORDER.DESC; //for current
        dv.Sort = "Address DESC";
        this.SortLabel.Text = "Current sorting order is descending";

    this.dgTest.DataSource = dv;


To minimize database access, we keep data in cache.

private DataTable  RetrieveDataFromDB()
    string SelectString = "select * from Employees";
    DataTable dt = new DataTable();
    using(SqlDataAdapter adpt = new 
          SqlDataAdapter(SelectString,this.NorthWindConnStr ))

    return dt;

private DataTable GetDataSource()
    object o;
    o = this.Cache[this.CacheKey];
    if (o != null)
        return (DataTable)o;
        DataTable dt = RetrieveDataFromDB();

        return dt;


Live Demo

You can download code to play with.


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


About the Author

United States United States
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralAdding Image with HeaderText Pin
varshavmane2-Mar-06 0:39
membervarshavmane2-Mar-06 0:39 
QuestionTransfer an event click to column header? Pin
hocviencsqg9-Dec-05 12:20
memberhocviencsqg9-Dec-05 12:20 
Hi billsheh,

In this example you instruct us how to transfer an event click from "Column Header" to NO-DISPLAY BUTTON.

I would appreciate it, if you can intruct me how to transfer an event click from BUTTON (visible) to "Column Header"; that means, when we click the BUTTON the DataGrid will be sorted by the indicate "Column Header"

Example: MyDataGrid consists of 3 columns: [Field], [Qualifier], and [Value].
A Web Control Button1.

When Button1_Click() it fires the Datagrid sorted by column [Field].

Thank you;

GeneralWrong cache usage Pin
rvachtl1-Jul-05 0:40
memberrvachtl1-Jul-05 0:40 
GeneralRe: Wrong cache usage Pin
billxie1-Jul-05 8:02
memberbillxie1-Jul-05 8:02 
GeneralMuch easier way... Pin
DanielHac8-Feb-05 2:23
memberDanielHac8-Feb-05 2:23 
GeneralRe: Much easier way... Pin
Jim Rogers23-Mar-05 5:41
memberJim Rogers23-Mar-05 5:41 
GeneralRe: Much easier way... Pin
Jay Dubal128-Aug-05 7:04
memberJay Dubal128-Aug-05 7:04 
GeneralRe: Much easier way... Pin
Jim Rogers28-Aug-05 7:14
memberJim Rogers28-Aug-05 7:14 
GeneralRe: Much easier way... Pin
M Cain10-Nov-05 13:42
memberM Cain10-Nov-05 13:42 
GeneralSorting more than one column Pin
abnorm2-Feb-05 8:58
memberabnorm2-Feb-05 8:58 
GeneralRe: Sorting more than one column Pin
billxie3-Feb-05 18:14
memberbillxie3-Feb-05 18:14 

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
Web04 | 2.8.180111.1 | Last Updated 14 Aug 2004
Article Copyright 2004 by billxie
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid