ASP.NET GridView Paging

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

ObjectDataSource

If using an ObjectDataSource, almost everything is handled for you already, just simply tell the GridView to AllowPaging and give it a PageSize.

<asp:GridView ID="gvColors"
    runat="server"
    DataSourceID="sdsColors"
    AllowPaging="True"
    PageSize="5">
</asp:GridView>

<asp:SqlDataSource ID="sdsColors"
    runat="server"
    ConnectionString="<%$ MyConnectionString %>"
    SelectCommand="SELECT Color_ID, Color_Name FROM Colors">
</asp:SqlDataSource>

Paging1Paging2Paging3

Manual Binding

If binding manually, you must handle the PageIndexChanging event. Simply set the DataSource and PageIndex and re-bind the GridView.

<asp:GridView ID="gvColors"
    runat="server"
    AllowPaging="True"
    PageSize="5"
    OnPageIndexChanging="gvColors_PageIndexChanging">
</asp:GridView>

C#

protected void gvColors_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    gvColors.DataSource = // Method to retrieve DataSource
    gvColors.PageIndex = e.NewPageIndex;
    gvColors.DataBind();
}

VB.NET

Protected Sub gvColors_PageIndexChanging(sender As Object, e As GridViewPageEventArgs)
{
    gvColors.DataSource = // Method to retrieve DataSource
    gvColors.PageIndex = e.NewPageIndex
    gvColors.DataBind()
}


Got any ASP.NET Question?