Monday, July 13, 2015

Implement Custom Attractive Pagination in Repeater Control in Asp.net Tips & Guide

In this tutorial I will explain how to Implement Custom Attractive Pagination In Repeater Control In Asp.net tips & guide.

Description:
By default Repeater control does not have pagination option. To implement the pagination in Repeater we have to write the custom code for it.
In this tutorial I am using two repeater control (one to bind the data and 2nd one to display page number) and 4 link buttons (to go page First, Last, Next and Previous page). On page load only 4 page numbers will be visible when user clicks on page number 4 next page numbers will be display and so on.

Implementation:-
Drag and drop the required controls from toolbox to webform. Add the given style in head section of webform.
     <style>
        .btncss
         {
padding:8px;
margin:2px;
background:#ffa100;
border:solid 1px #666;
font:8pt tahoma;
font-weight:bold;
color:#000;
        }
        table tr td
       {
           text-align:center;
          margin:5px;
           }
       table tr th
       {
            margin:5px;
            padding:5px;
           }
    </style>

Complete HTML markup of Webform:-

C#:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
        <style>
        .btncss
         {
padding:8px;
margin:2px;
background:#ffa100;
border:solid 1px #666;
font:8pt tahoma;
font-weight:bold;
color:#000;
        }
        table tr td
       {
           text-align:center;
          margin:5px;
           }
       table tr th
       {
            margin:5px;
            padding:5px;
           }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
        <tr><td>
            <asp:Repeater ID="rptsudentdetail" runat="server">
                <HeaderTemplate>
                    <table>
                          <thead>
            <tr>
                <th><b>Student Name</b> </th>
              <th>Fee</th>
                <th>Class </th>
                <th>Roll No.</th>
             </tr>
               </thead>
                </HeaderTemplate>
                <ItemTemplate>
                 <tr><td><%#DataBinder.Eval(Container, "DataItem.SudentName")%></td>
                     <td><%#DataBinder.Eval(Container, "DataItem.Fee")%></td>
                     <td><%#DataBinder.Eval(Container, "DataItem.StudentClass")%></td>
                     <td><%#DataBinder.Eval(Container, "DataItem.StudentRollNo")%></td>
                 </tr>
                </ItemTemplate>
            </asp:Repeater>
        </td></tr>
        <tr><td colspan="4"></td></tr>
        <tr><td></td></tr>
    </table>
        <table style="text-align:center;">
          <tr> <td>  <asp:LinkButton ID="lnkFirst" runat="server" CssClass="btncss"> << First</asp:LinkButton></td>
              <td> <asp:LinkButton ID="lnkPrevious" runat="server" CssClass="btncss"> < Previous </asp:LinkButton></td>
               <td><asp:Repeater ID="repeaterpaging" runat="server">
                         <ItemTemplate>
                                <asp:LinkButton ID="btnPage" CssClass="btncss"
                CommandName="Page" CommandArgument='<%# Eval("PageIndex") %>'
                                        Text='<%# Eval("PageText") %> '
                 runat="server" Font-Bold="True">
                                </asp:LinkButton>                           
           </ItemTemplate>
        </asp:Repeater></td>
             <td>  <asp:LinkButton ID="lnkNext" runat="server" CssClass="btncss">Next > </asp:LinkButton></td>
              <td><asp:LinkButton ID="lnkLast" runat="server" CssClass="btncss">Last >> </asp:LinkButton></td>
          </tr>
                </table>
    </div>
    </form>
</body>
</html>

VB:-
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
        <style>
        .btncss
         {
padding:8px;
margin:2px;
background:#ffa100;
border:solid 1px #666;
font:8pt tahoma;
font-weight:bold;
color:#000;
        }
        table tr td
       {
           text-align:center;
          margin:5px;
           }
       table tr th
       {
            margin:5px;
            padding:5px;
           }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table>
        <tr><td>
            <asp:Repeater ID="rptsudentdetail" runat="server">
                <HeaderTemplate>
                    <table>
                          <thead>
            <tr>
                <th><b>Student Name</b> </th>
              <th>Fee</th>
                <th>Class </th>
                <th>Roll No.</th>
             </tr>
               </thead>
                </HeaderTemplate>
                <ItemTemplate>
                 <tr><td><%#DataBinder.Eval(Container, "DataItem.SudentName")%></td>
                     <td><%#DataBinder.Eval(Container, "DataItem.Fee")%></td>
                     <td><%#DataBinder.Eval(Container, "DataItem.StudentClass")%></td>
                     <td><%#DataBinder.Eval(Container, "DataItem.StudentRollNo")%></td>
                 </tr>
                </ItemTemplate>
            </asp:Repeater>
        </td></tr>
        <tr><td colspan="4"></td></tr>
        <tr><td></td></tr>
    </table>
        <table style="text-align:center;">
          <tr> <td>  <asp:LinkButton ID="lnkFirst" runat="server" CssClass="btncss"> << First</asp:LinkButton></td>
              <td> <asp:LinkButton ID="lnkPrevious" runat="server" CssClass="btncss"> < Previous </asp:LinkButton></td>
               <td><asp:Repeater ID="repeaterpaging" runat="server">
                         <ItemTemplate>
                                <asp:LinkButton ID="btnPage" CssClass="btncss"
                CommandName="Page" CommandArgument='<%# Eval("PageIndex") %>'
                                        Text='<%# Eval("PageText") %> '
                 runat="server" Font-Bold="True">
                                </asp:LinkButton>                           
           </ItemTemplate>
        </asp:Repeater></td>
             <td>  <asp:LinkButton ID="lnkNext" runat="server" CssClass="btncss">Next > </asp:LinkButton></td>
              <td><asp:LinkButton ID="lnkLast" runat="server" CssClass="btncss">Last >> </asp:LinkButton></td>
          </tr>
                </table>
    </div>
    </form>
</body>
</html>

After design the webform. Now move to code file.

Add the namespace
C#:-
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
VB:-
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.Collections

Create connection
C#:-
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
VB:-
Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())

Write the code to bind the repeater and do pagination.
C#:-
  public static int totalPages = 0;
  int FirstIndex, LastIndex;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindRepeater();
        }
    }
    public int Pageno
    {
        get
        {
            if (ViewState["pagenumber"] != null)

                return Convert.ToInt32(ViewState["pagenumber"]);
            else
                return 0;
        }
        set
        {
            ViewState["pagenumber"] = value;
        }

    }
    public void BindRepeater()
    {
        try
        {
            SqlDataAdapter adp = new SqlDataAdapter("Select * from Student_Detail", con);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            PagedDataSource pagedatasource = new PagedDataSource();
            DataView dv = new DataView(dt);
            pagedatasource.DataSource = dv;
            pagedatasource.AllowPaging = true;
            pagedatasource.PageSize = 2;
            pagedatasource.CurrentPageIndex = Pageno;
            totalPages = pagedatasource.PageCount - 1;
            lnkPrevious.Enabled = !pagedatasource.IsFirstPage;
            lnkNext.Enabled = !pagedatasource.IsLastPage;
            lnkFirst.Enabled = !pagedatasource.IsFirstPage;
            lnkLast.Enabled = !pagedatasource.IsLastPage;
            ViewState["totpage"] = pagedatasource.PageCount;
            if (pagedatasource.PageCount > 1)
            {
                rptsudentdetail.DataSource = pagedatasource;
                rptsudentdetail.DataBind();

                DataTable dtnew = new DataTable();
                dtnew.Columns.Add("PageIndex");
                dtnew.Columns.Add("PageText");
                FirstIndex = Pageno - 2;
                if (Pageno > 2)
                {
                    LastIndex = Pageno + 2;
                }
                else
                {
                    LastIndex = 4;
                }
                if (LastIndex > Convert.ToInt32(ViewState["totpage"]))
                {
                    LastIndex = Convert.ToInt32(ViewState["totpage"]);
                    FirstIndex = LastIndex - 4;
                }

                if (FirstIndex < 0)
                {
                    FirstIndex = 0;
                }
                 for (int i = FirstIndex; i < LastIndex; i++)
                {
                    DataRow dr = dtnew.NewRow();
                    dr[0] = i;
                    dr[1] = i + 1;
                    dtnew.Rows.Add(dr);
                }
                repeaterpaging.DataSource = dtnew;
                repeaterpaging.DataBind();               
            }         
        }
        catch (Exception ex)
        {
        }
    }

VB:-
Public Shared totalPages As Integer = 0
Dim FirstIndex As Integer, LastIndex As Integer

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindRepeater()
        End If
    End Sub
    Public Property Pageno() As Integer
        Get
            If ViewState("pagenumber") IsNot Nothing Then
                Return Convert.ToInt32(ViewState("pagenumber"))
            Else
                Return 0
            End If
        End Get
        Set(value As Integer)
            ViewState("pagenumber") = value
        End Set
    End Property
    Public Sub BindRepeater()
        Try
            Dim adp As New SqlDataAdapter("Select * from Student_Detail", con)
            Dim dt As New DataTable()
            adp.Fill(dt)
            Dim pagedatasource As New PagedDataSource()
            Dim dv As New DataView(dt)
            pagedatasource.DataSource = dv
            pagedatasource.AllowPaging = True
            pagedatasource.PageSize = 2
            pagedatasource.CurrentPageIndex = Pageno
            totalPages = pagedatasource.PageCount - 1
            lnkPrevious.Enabled = Not pagedatasource.IsFirstPage
            lnkNext.Enabled = Not pagedatasource.IsLastPage
            lnkFirst.Enabled = Not pagedatasource.IsFirstPage
            lnkLast.Enabled = Not pagedatasource.IsLastPage
            ViewState("totpage") = pagedatasource.PageCount
            If pagedatasource.PageCount > 1 Then
                rptsudentdetail.DataSource = pagedatasource
                rptsudentdetail.DataBind()
                Dim dtnew As New DataTable()
                dtnew.Columns.Add("PageIndex")
                dtnew.Columns.Add("PageText")
                FirstIndex = Pageno - 2
                If Pageno > 2 Then
                    LastIndex = Pageno + 2
                Else
                    LastIndex = 4
                End If
                If LastIndex > Convert.ToInt32(ViewState("totpage")) Then
                    LastIndex = Convert.ToInt32(ViewState("totpage"))
                    FirstIndex = LastIndex - 4
                End If
                If FirstIndex < 0 Then
                    FirstIndex = 0
                End If
                For i As Integer = FirstIndex To LastIndex - 1
                    Dim dr As DataRow = dtnew.NewRow()
                    dr(0) = i
                    dr(1) = i + 1
                    dtnew.Rows.Add(dr)
                Next
                repeaterpaging.DataSource = dtnew
                repeaterpaging.DataBind()
            End If
        Catch ex As Exception
        End Try
    End Sub

Now write the code on link button click to move first, last, next and previous page number.
C#:-
protected void lnkFirst_Click(object sender, EventArgs e)
    {
        lnkFirst.Attributes["style"] = "background-color:black;color:#fff";
        lnkPrevious.Attributes["style"] = "";
        lnkLast.Attributes["style"] = "";
        lnkNext.Attributes["style"] = "";
        Pageno = 0;
        BindRepeater();
    }
    protected void lnkPrevious_Click(object sender, EventArgs e)
    {
        lnkPrevious.Attributes["style"] = "background-color:black;color:#fff";
        lnkFirst.Attributes["style"] = "";
        lnkLast.Attributes["style"] = "";
        lnkNext.Attributes["style"] = "";
        if (Pageno == 0)
        {
            Pageno = 0;
        }
        else
        {
            Pageno = Pageno - 1;
        }
        BindRepeater();
    }
    protected void lnkNext_Click(object sender, EventArgs e)
    {
        lnkNext.Attributes["style"] = "background-color:black;color:#fff";
        lnkFirst.Attributes["style"] = "";
        lnkPrevious.Attributes["style"] = "";
        lnkLast.Attributes["style"] = "";
        if (Pageno == totalPages)
        {
            Pageno = totalPages;
        }
        else
        {
            Pageno = Pageno + 1;
        }
        BindRepeater();
    }
    protected void lnkLast_Click(object sender, EventArgs e)
    {
        lnkLast.Attributes["style"] = "background-color:black;color:#fff";
        lnkFirst.Attributes["style"] = "";
        lnkPrevious.Attributes["style"] = "";
        lnkNext.Attributes["style"] = "";
        Pageno = (Convert.ToInt32(ViewState["totpage"]) - 1);
        BindRepeater();
    }

VB:-
Protected Sub lnkFirst_Click(sender As Object, e As EventArgs) Handles lnkFirst.Click
        lnkFirst.Attributes("style") = "background-color:black;color:#fff"
        lnkPrevious.Attributes("style") = ""
        lnkLast.Attributes("style") = ""
        lnkNext.Attributes("style") = ""
        Pageno = 0
        BindRepeater()
    End Sub
    Protected Sub lnkPrevious_Click(sender As Object, e As EventArgs) Handles lnkPrevious.Click
        lnkPrevious.Attributes("style") = "background-color:black;color:#fff"
        lnkFirst.Attributes("style") = ""
        lnkLast.Attributes("style") = ""
        lnkNext.Attributes("style") = ""
        If Pageno = 0 Then
            Pageno = 0
        Else
            Pageno = Pageno - 1
        End If
        BindRepeater()
    End Sub
    Protected Sub lnkNext_Click(sender As Object, e As EventArgs) Handles lnkNext.Click
        lnkNext.Attributes("style") = "background-color:black;color:#fff"
        lnkFirst.Attributes("style") = ""
        lnkPrevious.Attributes("style") = ""
        lnkLast.Attributes("style") = ""
        If Pageno = totalPages Then
            Pageno = totalPages
        Else
            Pageno = Pageno + 1
        End If
        BindRepeater()
    End Sub
    Protected Sub lnkLast_Click(sender As Object, e As EventArgs) Handles lnkLast.Click
        lnkLast.Attributes("style") = "background-color:black;color:#fff"
        lnkFirst.Attributes("style") = ""
        lnkPrevious.Attributes("style") = ""
        lnkNext.Attributes("style") = ""
        Pageno = (Convert.ToInt32(ViewState("totpage")) - 1)
        BindRepeater()
    End Sub

After that write the code on Repeater control events (ItemCommand, ItemDataBound) which we are using for paging.     
C#:-
protected void repeaterpaging_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        Pageno = Convert.ToInt32(e.CommandArgument.ToString());
        BindRepeater();
    }
    protected void repeaterpaging_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        LinkButton lnk = (LinkButton)e.Item.FindControl("btnPage");
        if (lnk.CommandArgument.ToString() == (Pageno).ToString())
        {
            lnk.ForeColor = System.Drawing.Color.Black;
        }
        else
        {
            {
                lnk.ForeColor = System.Drawing.Color.White;
            }
        } 
    }

VB:-
Protected Sub repeaterpaging_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles repeaterpaging.ItemDataBound
        Dim lnk As LinkButton = DirectCast(e.Item.FindControl("btnPage"), LinkButton)
        If lnk.CommandArgument.ToString() = (Pageno).ToString() Then
            lnk.ForeColor = System.Drawing.Color.Black
        Else
            If True Then
                lnk.ForeColor = System.Drawing.Color.White
            End If
        End If
    End Sub
    Protected Sub repeaterpaging_ItemCommand(source As Object, e As RepeaterCommandEventArgs) Handles repeaterpaging.ItemCommand
        Pageno = Convert.ToInt32(e.CommandArgument.ToString())
        BindRepeater()
    End Sub

Build, run the project and see the result.
 Result:
Implement Custom Attractive Pagination in Repeater Control in Asp.net Tips & Guide

Download the project:-
Download

 In this article we have learn how to implement the custom attractive pagination in repeater control in Asp.net(C#,VB). I hope you enjoyed this article. 

2 comments:

  1. Thanks for such a great tutorial...
    it works fine :)
    Thanks

    ReplyDelete
    Replies
    1. It was a pleasure. Keep visiting for more article

      Delete