Friday, September 10, 2010

Optimized Paging and Sorting in ASP.NET GridView

nbsp;Introduction

Paging and sorting are most commonly used features of ASP.NET GridView. And it is very easy to use/implement these features in GridView with small chunk of lines. In this article I am going to demonstrate what are the performance drawbacks of using conventional way to page and sort your GridView and then I will demonstrate 'An Optimized way to implement Paging and Sorting'.
What are conventional steps for Paging and Sorting?

Usually we perform the following steps to enable paging and sorting in our GridView.

1. Set AllowPaging and AllowSorting Properties of GridView to True to enable paging and sorting respectively e.g
view sourceprint?
1.<asp:GridView ID="GridView1" runat="server" AllowPaging="true" AllowSorting="true"  >
2. </asp:GridView>

2. Set the PageSize property to mention how many records will be display on each page.

3. Set the SortExpression property of each column. By default each Data Bound columns has the bounded column name as default value for the SortExpression property.

4. Handle PageIndexChanging and Sorting Events of GridView to respond to paging and sorting actions respectively, like so:
view sourceprint?
<asp:GridView ID="GridView1" runat="server" AllowPaging="true"
            AllowSorting="true" onpageindexchanging="GridView1_PageIndexChanging"
            onsorting="GridView1_Sorting"  >
        </asp:GridView>
 protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
}
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
}

5. Put some logic in the event handlers to do their jobs