Paging in a GridView control allows you to display a subset of data at a time, improving performance and user experience. This is particularly useful when dealing with large datasets. In this guide, we will walk through the steps to implement paging in a GridView control in ASP.NET Web Forms.

Steps to Implement Paging in GridView

  1. Set Up the GridView Control: Define the GridView in your ASPX page and enable paging.
  2. Bind Data to the GridView: Create a method to bind data to the GridView.
  3. Handle the PageIndexChanging Event: Implement the event handler to manage page changes.

Sample Code for Paging in GridView

Below is a complete example demonstrating how to implement paging in a GridView control.

1. Define the Product Class


public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public decimal Price { get; set; }
}

2. Create a Method to Get Sample Data


public List<Product> GetProducts()
{
// Simulating a data source with a large number of products
List<Product> products = new List<Product>();
for (int i = 1; i <= 100; i++)
{
products.Add(new Product { ProductID = i, ProductName = "Product " + i, Price = i * 10 });
}
return products;
}

3. Add the GridView Control to the ASPX Page


<asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="false"
AllowPaging="true" PageSize="10" OnPageIndexChanging="gvProducts_PageIndexChanging">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="ID" />
<asp:BoundField DataField="ProductName" HeaderText="Product Name" />
<asp:BoundField DataField="Price" HeaderText="Price" />
</Columns>
</asp:GridView>

4. Code-Behind to Bind Data


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}

private void BindGrid()
{
gvProducts.DataSource = GetProducts();
gvProducts.DataBind();
}

5. Implement the PageIndexChanging Event

To handle paging, you need to implement the PageIndexChanging event:


protected void gvProducts_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvProducts.PageIndex = e.NewPageIndex; // Set the new page index
BindGrid(); // Rebind the data to the GridView
}

Conclusion

Implementing paging in a GridView control is straightforward and enhances the usability of your web application. By following the steps outlined above, you can efficiently manage large datasets and provide a better user experience. The GridView control's built-in paging capabilities make it a powerful tool for displaying data in ASP.NET Web Forms applications.