ASP.NET GridView Paging and Sorting

Below is the sample to include Sorting and Paging in ASP.Net GridView.

ASPX Code


<asp:GridView ID="grd" runat="server" AutoGenerateColumns="False"
               
AllowSorting="true" OnSorting="grd_Sorting"
               
AllowPaging="true" PageSize="50" OnPageIndexChanging="grd_PageIndexChanging">

Code Behind


protected void grd_Sorting(object sender, GridViewSortEventArgs e)
       
{
           
try
           
{
                mDT
= GetData();
               
               
SetSortDirection(SortDirection);
               
if (mDT != null)
               
{                    
                    mDT
.DefaultView.Sort = e.SortExpression + " " + _sortDirection;
                    grd
.DataSource = mDT;
                    grd
.DataBind();
                   
SortDirection = _sortDirection;
               
}
           
}
           
catch(Exception exp)
           
{
           
}
       
}

protected void grd_PageIndexChanging(object sender, GridViewPageEventArgs e)
       
{
            grdList
.PageIndex = e.NewPageIndex;

           
try
           
{
                mDT
= GetData();
               
               
SetSortDirection(SortDirection);
               
if (mDT != null)
               
{
                   
                    grd
.DataSource = mDT;
                    grd
.DataBind();
                   
SortDirection = _sortDirection;
               
}
               
           
}
           
catch (Exception exp)
           
{
           
}
       
}

GridView Sort not working when AutoGenerateColumns = False
Need to set SortExpression to the columns manually (SortExpression=”datafield” ), when AutoGenerateColumns=”false”. If AutoGenerateColumns=”True”, then DataGrid sets SortExpression automatically based on the field name.


<asp:BoundField DataField="datacolumn" SortExpression="datacolumn" HeaderText="Data Header">

Leave a Reply

Your email address will not be published.