In this article I will explain with an example, how to implement paging in GridView using Entity Framework in ASP.Net using C# and VB.Net.
 
 

Database

Here I am making use of Microsoft’s Northwind Database. You can download it from here.
 
 

Configuring and connecting Entity Framework to database

First, you need to configure and connect Entity Framework to database.
Note: For more details on how to configure and connect Entity Framework to database, please refer my article Configure Entity Framework Step By Step in ASP.Net.
 
 

HTML Markup

The following HTML Markup consists of:
GridView – For displaying the records.
The GridView consists of four BoundField columns.
<asp:GridView runat="server" ID="gvCustomers" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField HeaderText="CustomerID" DataField="CustomerID" />
        <asp:BoundField HeaderText="Contact Name" DataField="ContactName" />
        <asp:BoundField HeaderText="City" DataField="City" />
        <asp:BoundField HeaderText="Country" DataField="Country" />
    </Columns>
</asp:GridView>
 

Repeater for implementing pager

The Repeater control has the following template:
ItemTemplate – The content of this template will be repeated for each record present in its DataSource.
The ItemTemplate consists of a LinkButton.
The LinkButton has been assigned with following properties:
Text – For setting the LinkButton Text.
CssClass – For applying style.
Note: The HTML Markup has C# and VB.Net code to swap the CSS style classes for the Current Page and the remaining pages, so that the Current Page is viewed distinguished from others.
For more details please refer my article, Using IF ELSE condition in ItemTemplate of Repeater in ASP.Net.
 
The LinkButton has been assigned with OnClick and OnClientClick event handler.
C#
<asp:Repeater ID="rptPager" runat="server">
    <ItemTemplate>
        <asp:LinkButton ID="lnkPage" runat="server" Text='<%#Eval("Text") %>' CommandArgument='<%# Eval("Value") %>'
            CssClass='<%#Convert.ToBoolean(Eval("Enabled")) ? "page_enabled" : "page_disabled" %>'
            OnClick="Page_Changed" OnClientClick='<%# !Convert.ToBoolean(Eval("Enabled")) ? "return false;" : "" %>'></asp:LinkButton>
    </ItemTemplate>
</asp:Repeater>
 
VB.Net
<asp:Repeater ID="rptPager" runat="server">
    <ItemTemplate>
        <asp:LinkButton ID="lnkPage" runat="server" Text='<%#Eval("Text") %>' CommandArgument='<%# Eval("Value") %>'
            CssClass='<%#If(Convert.ToBoolean(Eval("Enabled")), "page_enabled", "page_disabled")%>'
            OnClick="Page_Changed" OnClientClick='<%#If(Not Convert.ToBoolean(Eval("Enabled")), "return false;", "") %>'></asp:LinkButton>
    </ItemTemplate>
</asp:Repeater>
 
 

Generic Method to populate GridView

The following method is used throughout this article to populate GridView and Repeater.
It accepts the pageIndex as parameter.
Inside the BindGrid method, the records from the Customers table are fetched using Entity Framework and assigned to the DataSource property of the GridView control.
The Paging is performed on the records using the Skip and Take functions.
 

Skip function

The Skip function accepts the Start Index from the set of records to fetched i.e. if Page Index is 1 then the Start Index will be ( 1 - 1) * 10 = 0.
Example: If Current Page Index is 1 and the Maximum Rows is 10, then the Start Index will be (1 - 1) * 10 = 0.
 

Take function

The Take function will fetch the rows based on the value of the PageSize property.
Finally, the PopulatePager method is called along with the total Record Count and PageIndex.
C#
private int PageSize = 10;
protected void BindGrid(int pageIndex)
{
    NorthwindEntities entities = new NorthwindEntities();
    gvCustomers.DataSource = (from customer in entities.Customers
                              select customer)
                             .OrderBy(x => x.CustomerID)
                             .Skip((pageIndex - 1) * PageSize)
                             .Take(PageSize).ToList();
    gvCustomers.DataBind();
    this.PopulatePager(entities.Customers.Count(), pageIndex);
}
 
VB.Net
Private PageSize As Integer = 10
Protected Sub BindGrid(ByVal pageIndex As Integer)
    Dim entities As NorthwindEntities = New NorthwindEntities()
    gvCustomers.DataSource = (From customer In entities.Customers
                              Select customer) _
                            .OrderBy(Function(x) x.CustomerID) _
                            .Skip((pageIndex - 1) * PageSize) _
                            .Take(PageSize).ToList()
    gvCustomers.DataBind()
    Me.PopulatePager(entities.Customers.Count(), pageIndex)
End Sub
 
 

Populating the Pager

The PopulatePager method accepts the count of the total records present in the Table and the current PageIndex.
Then, a check is performed to find the first and the last page of the pager and then FOR loop is executed and List of Pages is populated.
The Pages assigned to the DataSource property of Repeater control.
Finally, the Repeater control is populated.
C#
private void PopulatePager(int recordCount, int currentPage)
{
    List<ListItem> pages = new List<ListItem>();
    int startIndex, endIndex;
    int pagerSpan = 5;
 
    //Calculate the Start and End Index of pages to be displayed.
    double dblPageCount = (double)((decimal)recordCount / Convert.ToDecimal(PageSize));
    int pageCount = (int)Math.Ceiling(dblPageCount);
    startIndex = currentPage > 1 && currentPage + pagerSpan - 1 < pagerSpan ? currentPage : 1;
    endIndex = pageCount > pagerSpan ? pagerSpan : pageCount;
    if (currentPage > pagerSpan % 2)
    {
        if (currentPage == 2)
       {
            endIndex = 5;
        }
        else
        {
            endIndex = currentPage + 2;
        }
    }
    else
    {
        endIndex = (pagerSpan - currentPage) + 1;
    }
 
    if (endIndex - (pagerSpan - 1) > startIndex)
    {
        startIndex = endIndex - (pagerSpan - 1);
    }
 
    if (endIndex > pageCount)
    {
        endIndex = pageCount;
        startIndex = ((endIndex - pagerSpan) + 1) > 0 ? (endIndex - pagerSpan) + 1 : 1;
    }
 
    //Add the First Page Button.
    if (currentPage > 1)
    {
        pages.Add(new ListItem("First", "1"));
    }
 
    //Add the Previous Button.
    if (currentPage > 1)
    {
        pages.Add(new ListItem("<<", (currentPage - 1).ToString()));
    }
 
    for (int i = startIndex; i <= endIndex; i++)
    {
        pages.Add(new ListItem(i.ToString(), i.ToString(), i != currentPage));
    }
 
    //Add the Next Button.
    if (currentPage < pageCount)
    {
        pages.Add(new ListItem(">>", (currentPage + 1).ToString()));
    }
 
    //Add the Last Button.
    if (currentPage != pageCount)
    {
        pages.Add(new ListItem("Last", pageCount.ToString()));
    }
    rptPager.DataSource = pages;
    rptPager.DataBind();
}
 
VB.Net
Private Sub PopulatePager(ByVal recordCount As Integer, ByVal currentPage As Integer)
    Dim pages As List(Of ListItem) = New List(Of ListItem)()
    Dim startIndex, endIndex As Integer
    Dim pagerSpan As Integer = 5
 
    'Calculate the Start and End Index of pages to be displayed.
    Dim dblPageCount As  Double = CDbl((CDec(recordCount) / Convert.ToDecimal(PageSize)))
    Dim pageCount As Integer = CInt(Math.Ceiling(dblPageCount))
    startIndex = If(currentPage > 1 AndAlso currentPage + pagerSpan - 1 < pagerSpan, currentPage, 1)
    endIndex = If(pageCount > pagerSpan, pagerSpan, pageCount)
 
    If currentPage > pagerSpan Mod 2 Then
 
        If currentPage = 2 Then
            endIndex = 5
        Else
            endIndex = currentPage + 2
        End If
    Else
        endIndex = (pagerSpan - currentPage) + 1
    End If
 
    If endIndex - (pagerSpan - 1) > startIndex Then
        startIndex = endIndex - (pagerSpan - 1)
    End If
 
    If endIndex > pageCount Then
        endIndex = pageCount
        startIndex = If(((endIndex - pagerSpan) + 1) > 0, (endIndex - pagerSpan) + 1, 1)
    End If
 
    'Add the First Page Button.
    If currentPage > 1 Then
        pages.Add(New ListItem("First", "1"))
    End If
 
    'Add the Previous Button.
    If currentPage > 1 Then
        pages.Add(New ListItem("<<", (currentPage - 1).ToString()))
    End If
 
    For i As Integer = startIndex To endIndex
        pages.Add(New ListItem(i.ToString(), i.ToString(), i <> currentPage))
    Next
 
    'Add the Next Button.
    If currentPage < pageCount Then
        pages.Add(New ListItem(">>", (currentPage + 1).ToString()))
    End If
 
    'Add the Last Button.
    If currentPage <> pageCount Then
        pages.Add(New ListItem("Last", pageCount.ToString()))
    End If
    rptPager.DataSource = pages
    rptPager.DataBind()
End Sub
 
 

Binding the GridView control in Page Load

Inside the Page_Load event handler, the BindGrid method is called and the PageIndex parameter value is passed 1, so that initially it will load the first page.
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid(1);
    }
}
 
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Me.BindGrid(1)
    End If
End Sub
 
 

Binding the GridView on Pager LinkButton Click

When Page Number LinkButton is clicked, the PageIndex is referenced using LinkButton CommandArgument property.
Finally, BindGrid method is called by passing the PageIndex value.
C#
protected void Page_Changed(object sender, EventArgs e)
{
    int pageIndex = int.Parse((sender as LinkButton).CommandArgument);
    this.BindGrid(pageIndex);
}
 
VB.Net
Protected Sub Page_Changed(ByVal sender As Object, ByVal e As EventArgs)
    Dim pageIndex As Integer = Integer.Parse((TryCast(sender, LinkButton)).CommandArgument)
    Me.BindGrid(pageIndex)
End Sub
 
 

Screenshot

Implement Paging in ASP.Net GridView using EntityFramework
 
 

Demo

 
 

Downloads