Paging in GridView in ASP.Net c#

Paging in GridView in ASP.Net c#

In this post, we will explain how to implement Paging (Pagination) in GridView control in ASP.Net using C#

The following in order to implement Paging in GridView, AllowPaging property is set to true and OnPageIndexChanging event has been handled. HTML Markup code of an ASP.Net GridView with four BoundField columns.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" AllowPaging="true"
    OnPageIndexChanging="OnPageIndexChanging" PageSize="10">
    <Columns>
        <asp:BoundField ItemStyle-Width="200px" DataField="CustomerID" HeaderText="Customer ID" />
        <asp:BoundField ItemStyle-Width="200px" DataField="ContactName" HeaderText="Contact Name" />
        <asp:BoundField ItemStyle-Width="200px" DataField="City" HeaderText="City" />
        <asp:BoundField ItemStyle-Width="200px" DataField="Country" HeaderText="Country" />
    </Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid();
    }
}
 
private void BindGrid()
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, ContactName, City, Country FROM tbl_Country"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }
        }
    }
}

2020-02-23