Latest update Android YouTube

Pagination in GridView: A Comprehensive Guide

Pagination in GridView: A Comprehensive Guide

Pagination in GridView: A Comprehensive Guide

Pagination is a crucial feature in data-driven applications, especially when dealing with large datasets. It allows you to display data in smaller, more manageable chunks (pages) rather than loading all records at once. In ASP.NET, the GridView control provides built-in support for pagination, making it easy to implement this functionality.

Pagination in GridView: A Comprehensive Guide

In this blog post, we'll explore how to implement pagination in GridView, handle search functionality, and manage pagination events with detailed examples.

What is Pagination in GridView?

Pagination in GridView divides a large dataset into multiple pages, allowing users to navigate through the data using page numbers or navigation buttons. This improves performance and usability by reducing the amount of data loaded at once.

1. Enabling Pagination in GridView

To enable pagination in GridView, you need to set the AllowPaging property to true and handle the PageIndexChanging event.

Step 1: Set AllowPaging Property

Add the GridView control to your ASP.NET page and set the AllowPaging property:

<asp:GridView
    ID="agentsGrid"
    CssClass="table table-hover"
    AutoGenerateColumns="false"
    AllowPaging="True"
    PageSize="20"
    OnPageIndexChanging="superANAAgentSearchListDetailsGridsbl_PageIndexChanging"
    DataKeyNames="AGENT_CODE"
    runat="server">
    <Columns>
        <asp:TemplateField>
            <HeaderTemplate>
                <asp:CheckBox ID="chkHeader" runat="server" AutoPostBack="True" OnCheckedChanged="chkHeader_CheckedChanged" />
            </HeaderTemplate>
            <ItemTemplate>
                <asp:CheckBox ID="chkSelect" runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Agent Code" ItemStyle-CssClass="column-width-100">
            <ItemTemplate>
                <asp:Label ID="lblAgentCodeSearched" runat="server" Text='<%# Eval("Agent_Code") %>' Visible="true" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Agent Name" ItemStyle-CssClass="column-width-100">
            <ItemTemplate>
                <asp:Label ID="lblAgentNameSearched" runat="server" Text='<%# Eval("Agent_Name") %>' Visible="true" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Exist Code" ItemStyle-CssClass="column-width-100">
            <ItemTemplate>
                <asp:Label ID="lblExistCodeSearched" runat="server" Text='<%# Eval("Exist_Code") %>' Visible="true" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Address 1" ItemStyle-CssClass="column-width-100">
            <ItemTemplate>
                <asp:Label ID="lblAddress1Searched" runat="server" Text='<%# Eval("Address1") %>' Visible="true" />
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Address 2" ItemStyle-CssClass="column-width-100">
            <ItemTemplate>
                <asp:Label ID="lblAddress2Searched" runat="server" Text='<%# Eval("Address2") %>' Visible="true" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Step 2: Handle the PageIndexChanging Event

In the code-behind, handle the PageIndexChanging event to update the current page index and rebind the data:

protected void superANAAgentSearchListDetailsGridsbl_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    // Update the page index
    agentsGrid.PageIndex = e.NewPageIndex;

    // Re-bind the data with the updated page index
    BindGridForSuperANASearchPaging();
}

2. Implementing Search Functionality

To implement search functionality, you need to capture user input, filter the data, and bind the filtered data to the GridView.

Step 1: Capture User Input

Add input fields and a search button to your ASP.NET page:

<div class="row">
    <div class="col-md-3">
        <label class="form-label" for="sourceid">Branch</label>
        <asp:DropDownList ID="ddlSourceID" CssClass="form-select" runat="server" AutoPostBack="True" OnSelectedIndexChanged="RM_ddlSourceID_SelectedIndexChanged">
            <asp:ListItem Value="0">Select</asp:ListItem>
        </asp:DropDownList>
    </div>
    <div class="col-md-3">
        <label class="form-label" for="rmsbl">Agent</label>
        <asp:DropDownList ID="ddlRM" CssClass="form-select" runat="server">
            <asp:ListItem Value="0">Select</asp:ListItem>
            <asp:ListItem Value="rm1">RM 1</asp:ListItem>
            <asp:ListItem Value="rm2">RM 2</asp:ListItem>
        </asp:DropDownList>
    </div>
    <div class="col-md-3">
        <label class="form-label" for="agentname">Agent Name</label>
        <asp:TextBox ID="txtAgentName" CssClass="form-control" runat="server" placeholder="Enter Agent Name" />
    </div>
    <div class="col-md-3">
        <label class="form-label" for="existcode">Exist Code</label>
        <asp:TextBox ID="txtExistCode" CssClass="form-control" runat="server" placeholder="Enter Exist Code"></asp:TextBox>
    </div>
</div>
<div class="row mt-1">
    <div class="col-md-9 mt-2 text-end">
        <asp:Button
            ID="btnSearch"
            CssClass="btn btn-primary ms-2"
            Text="Search"
            runat="server"
            OnClick="btnSearch_Click_SuperAna"
            CausesValidation="false" />
    </div>
</div>

Step 2: Handle the Search Button Click

In the code-behind, handle the search button click event to filter the data and bind it to the GridView:

protected void btnSearch_Click_SuperAna(object sender, EventArgs e)
{
    // First, validate if at least one search field is filled
    if (!IsSuperANASearchCriteriaFilled())
    {
        string emptyFieldMsg = "Please fill at least one search field";
        if (agentsGrid.Rows.Count > 0)
        {
            agentsGrid.DataSource = null;
            agentsGrid.DataBind();
        }
        ShowAlert(emptyFieldMsg);
        lblSuperAnamsg.Text = emptyFieldMsg;
        return;
    }

    // Store search parameters in ViewState for pagination
    ViewState["VS_SAS_SOURCEID"] = ddlSourceID.SelectedValue == "0" ? (int?)null : (int.TryParse(ddlSourceID.SelectedValue, out int sourceId) ? (int?)sourceId : null);
    ViewState["VS_SAS_RM_CODE"] = ddlRM.SelectedValue == "0" ? (int?)null : (int.TryParse(ddlRM.SelectedValue, out int rmCode) ? (int?)rmCode : null);
    ViewState["VS_SAS_AGENT_NAME"] = string.IsNullOrEmpty(txtAgentName.Text) ? null : txtAgentName.Text.Trim();
    ViewState["VS_SAS_EXIST_CODE"] = string.IsNullOrEmpty(txtExistCode.Text) ? null : txtExistCode.Text.Trim();

    // Reset the page index to 0 when performing a new search
    agentsGrid.PageIndex = 0;

    // Call BindGrid with stored parameters
    BindGridForSuperANASearchPaging();
}

Step 3: Bind Filtered Data to GridView

Bind the filtered data to the GridView and handle pagination:

private void BindGridForSuperANASearchPaging()
{
    int? SOURCEID = ViewState["VS_SAS_SOURCEID"] as int?;
    int? RM_CODE = ViewState["VS_SAS_RM_CODE"] as int?;
    string AGENT_NAME = ViewState["VS_SAS_AGENT_NAME"] as string;
    string EXIST_CODE = ViewState["VS_SAS_EXIST_CODE"] as string;

    // Get the filtered data for the current page
    DataTable dt = new WM.Controllers.AgentController().GetFilteredAgentsData(SOURCEID, RM_CODE, AGENT_NAME, EXIST_CODE);

    // Get the total rows count for pagination
    int totalRowsCount = dt.Rows.Count;

    // Handle data binding and GridView visibility
    if (totalRowsCount > 0)
    {
        lblSuperAnamsg.Text = $"Total {totalRowsCount} Record{(totalRowsCount == 1 ? "" : "s")} found";
        agentsGrid.Visible = true;
        agentsGrid.DataSource = dt;
        agentsGrid.DataBind();

        // Set pagination controls
        agentsGrid.PageSize = 20;  // Set the page size to 20
    }
    else
    {
        ResetAssociateListGrid();
        lblSuperAnamsg.Text = "No records found!";
        agentsGrid.Visible = false;
    }
}

Get Here!

3. Best Practices for Pagination

  • Use Server-Side Pagination: For large datasets, fetch only the records for the current page from the database to improve performance.
  • Store Search Parameters: Store search parameters in ViewState or Session to maintain state during pagination.
  • Optimize Database Queries: Use efficient SQL queries and indexing to improve data retrieval performance.
  • Provide Feedback: Display the total number of records and the current page number to the user.

Conclusion

Pagination is a powerful feature of GridView that enhances the performance and usability of your data-driven applications. By enabling pagination, implementing search functionality, and handling pagination events, you can provide users with a seamless experience for navigating through large datasets. Experiment with the examples provided and explore more advanced techniques to take your skills to the next level.

Post a Comment

Feel free to ask your query...
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.