How To Create Sorting And Paging In ASP.NET Web Forms GridView

 1. First, Create A  YourPage.aspx Page  In Your Application

   To add sorting and paging to an ASP.NET GridView, you need to follow these steps:

  1. Enable Sorting and Paging: You can enable sorting and paging by setting the AllowSorting and AllowPaging properties to True.
  2. Set Page Size: The PageSize property allows you to define the number of records displayed per page.
  3. Handle Sorting and Paging Events: You need to handle the Sorting and PageIndexChanging events to manage sorting and paging functionality.
  4. Bind Data: Ensure the GridView is bound to a data source on each postback to maintain the state of sorting and paging.

Example Code

Here is a complete example of an ASP.NET GridView with sorting and paging enabled:

<div id="dvGrid" class="row-fluid" style="overflow: auto;">
     <asp:GridView ID="MDetails" runat="server" AutoGenerateColumns="False" CellPadding="3"
         Width="100%" AllowPaging="True" AllowSorting="True" CssClass="GridStyle" PageSize="50"
         OnSorting="MDetails_Sorting" OnPageIndexChanging="MDetails_PageIndexChanging"
         BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" GridLines="None" Style="line-height: 25px;">
         <columns>
             <asp:TemplateField HeaderText="क्र.">
                 <itemtemplate>
                    <%# ((GridViewRow) Container).RowIndex + 1 + (MDetails.PageIndex * MDetails.PageSize) %>
                 </itemtemplate>
             </asp:TemplateField>
             <asp:BoundField DataField="DistrictName" HeaderText="नाम" SortExpression="Name" />
             <asp:BoundField DataField="LocalName" HeaderText="निकाय का नाम " SortExpression="LocalName" />
             <asp:BoundField DataField="ZoneName" HeaderText="ग्राम" SortExpression="Zone" />
             <asp:BoundField DataField="Village" HeaderText="/वार्ड" SortExpression="WardName" />
             <asp:BoundField DataField="Id" HeaderText="आईडी" SortExpression="Id" />
             <asp:BoundField DataField="NewId" HeaderText="आईडी" SortExpression="Id" />
             <asp:BoundField DataField="MemberName" HeaderText="हितग्राही नाम" SortExpression="MemberName">
                 <itemstyle horizontalalign="Left"></itemstyle>
             </asp:BoundField>
             <asp:BoundField DataField="Date" DataFormatString="{0:dd/MM/yyyy}" HeaderText="दिनाकं" SortExpression="Date" />
             <asp:TemplateField HeaderText="विवरण देखे">
                 <itemtemplate>
                     <asp:Button ID="btnViewDetails" runat="server" Text="देखें" CssClass="btn btn-success btn-sm"
                         OnClick='<%# "return showDetailsPopup(" + Eval("ID") +");" %>' />
                     <asp:Label ID="lblmsg1" runat="server" Text="" Visible="false"></asp:Label>
                 </itemtemplate>
                 <itemstyle width="80px" horizontalalign="Center"></itemstyle>
             </asp:TemplateField>
         </columns>
         <footerstyle backcolor="White" forecolor="#000066" />
         <headerstyle backcolor="#006699" font-bold="True" forecolor="White" />
         <headerstyle backcolor="#0e4d92" font-bold="True" forecolor="White" />
         <pagerstyle backcolor="White" forecolor="#000066" horizontalalign="Left" />
         <rowstyle forecolor="#000066" />
         <selectedrowstyle backcolor="#669999" font-bold="True" forecolor="White" />
         <sortedascendingcellstyle backcolor="#F1F1F1" />
         <sortedascendingheaderstyle backcolor="#007DBB" />
         <sorteddescendingcellstyle backcolor="#CAC9C9" />
         <sorteddescendingheaderstyle backcolor="#00547E" />
     </asp:GridView>
 </div>

2. Now In Your YourPage.cs Page Add Method Of Sorting And Paging


Key Points of Sorting and Paging in Code-Behind

Sorting Event Handler (MDetails_Sorting)

​protected void MDetails_Sorting(object sender, GridViewSortEventArgs e)
{
    DataTable dt = ViewState["FamilyDetails"] as DataTable;
    if (dt != null)
    {
        dt.DefaultView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);
        MDetails.DataSource = dt;
        MDetails.DataBind();
    }
}

​
  • Event Trigger: This method is triggered when a column header is clicked to sort the GridView.
  • Retrieve Data: Retrieve the data from ViewState.
  • Sort Data: Sort the data based on the clicked column (e., SortExpression) and the sort direction.
  • Rebind Data: Binds the sorted data back to the GridView.

2. Paging Event Handler (MDetails_PageIndexChanging)

protected void MDetails_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    MDetails.PageIndex = e.NewPageIndex;
    BindGridView();
}
  • Event Trigger: This method is triggered when a different page is selected in the GridView.
  • Set Page Index: Updates the PageIndex of the GridView to the new page index.
  • Rebind Data: Calls BindGridView() to rebind the data and refresh the GridView with the new page.

3. Get Sort Direction (GetSortDirection)

private string GetSortDirection(string column)
{
    string sortDirection = "ASC";
    string sortExpression = ViewState["SortExpression"] as string;
    if (sortExpression != null)
    {
        if (sortExpression == column)
        {
            string lastDirection = ViewState["SortDirection"] as string;
            if ((lastDirection != null) && (lastDirection == "ASC"))
            {
                sortDirection = "DESC";
            }
        }
    }
    ViewState["SortDirection"] = sortDirection;
    ViewState["SortExpression"] = column;
    return sortDirection;
}
  • Purpose: Determines the sort direction (ascending or descending) based on the current column.
  • State Management: Uses ViewState to store and retrieve the current sort direction and expression.

4. Bind Data (BindGridView)

private void BindGridView()
{       
    DataTable dt = GetFamilyDetails();
    ViewState["FamilyDetails"] = dt;
    MDetails.DataSource = dt;
    MDetails.DataBind();
}
  • Purpose: Binds the GridView with data.
  • Data Retrieval: Calls GetFamilyDetails() to fetch the data.
  • State Management: Stores the data in ViewState for later use (sorting, paging).
  • Bind Data: Binds the data to the GridView control.


Similar Articles