Wednesday, July 15, 2015

Implement Google like Custom Pagination in Datalist Control in Asp.net

In this tutorial I try to explain how to implement Google like custom pagination in Datalist control in asp.net

Description:

Implementation:
By default Datalist data control doesn’t have paging option. So we have to write the custom code to implement the pagination functionality. In this tutorial I am going to implement the pagination in Datalist data control like Google.
To implement this I am using Two Datalist control (One to display Data and another one for pagination) and two link buttons to go Next and previous page. So drag and drop the required controls from the toolbox to webform.
Add the style to Head section of webform

<style>
        .btncss
         {
padding:8px;
margin:2px;
background:#5BCFEA;
border:solid 1px #666;
  color: #fff;
  text-decoration: none;
        }
         .btncss:hover {
background:#4BA5DB;
         }
       table tr td
       {
           text-align:center;
          margin:5px;
           }
       table tr th
       {
            margin:5px;
            padding:5px;
           }
    </style>

HTML markup of Webform:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
     <style>
        .btncss
         {
padding:8px;
margin:2px;
background:#5BCFEA;
border:solid 1px #666;
  color: #fff;
  text-decoration: none;
        }
         .btncss:hover {
background:#4BA5DB;
         }
       table tr td
       {
           text-align:center;
          margin:5px;
           }
       table tr th
       {
            margin:5px;
            padding:5px;
           }
    </style>
</head>
<body>
    <form id="form1" runat="server">
     <asp:DataList ID="dlstudentdetail" runat="server">
            <HeaderTemplate>
                <table>
                          <thead>          
                <th>Student Name</th>
              <th>Fee</th>
                <th>Class </th>
                <th>Roll No.</th>         
               </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:DataList>
        <table>
            <tr><td></td></tr>
            <tr><td></td></tr>
            <tr><td> <asp:LinkButton Visible="false" ID="lnkPrevious" runat="server" CssClass="btncss">Previous </asp:LinkButton></td>
                <td>
                     <asp:DataList ID="dlpaging" runat="server" RepeatDirection="Horizontal">
            <ItemTemplate>
                 <asp:LinkButton ID="btnPage" CssClass="btncss"
                CommandName="Page" CommandArgument='<%# Eval("PageIndex") %>'
                                        Text='<%# Eval("PageText") %> '
                 runat="server" Font-Bold="True">
                                </asp:LinkButton> 
            </ItemTemplate>
        </asp:DataList>
                </td>
                        <td>  <asp:LinkButton ID="lnkNext" runat="server" CssClass="btncss">Next </asp:LinkButton></td>
            </tr>
            <tr><td></td><td></td><td></td></tr>
        </table>
    </form>
</body>
</html>
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. Write the code to Bind the datalist and for pagination.
C#:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());
    public static int totalPages = 0;
    int FirstIndex, LastIndex;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDataList();
        }
    }
    public int Pageno
    {
        get
        {
            if (ViewState["pagenumber"] != null)

                return Convert.ToInt32(ViewState["pagenumber"]);
            else
                return 0;
        }
        set
        {
            ViewState["pagenumber"] = value;
        }
    }
    public void BindDataList()
    {
        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;
            lnkNext.Enabled = !pagedatasource.IsLastPage;
            lnkPrevious.Enabled = !pagedatasource.IsFirstPage;
            ViewState["totpage"] = pagedatasource.PageCount;
            if (pagedatasource.PageCount > 1)
            {
                dlstudentdetail.DataSource = pagedatasource;
                dlstudentdetail.DataBind();
                DataTable dtnew = new DataTable();
                dtnew.Columns.Add("PageIndex");
                dtnew.Columns.Add("PageText");
                FirstIndex = Pageno - 5;
                if (Pageno > 5)
                {
                    LastIndex = Pageno + 5;
                    lnkPrevious.Visible = true;
                }
                else
                {
                    LastIndex = 10;
                }
                if (LastIndex > Convert.ToInt32(ViewState["totpage"]))
                {
                    LastIndex = Convert.ToInt32(ViewState["totpage"]);
                    FirstIndex = LastIndex - 5;
                }
                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);
                }
                dlpaging.DataSource = dtnew;
                dlpaging.DataBind();
            }         
        }
        catch (Exception ex)
        {
        }
    }

VB:
Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())
    Public Shared totalPages As Integer = 0
    Private FirstIndex As Integer, LastIndex As Integer
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If Not IsPostBack Then
            BindDataList()
        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 BindDataList()
     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
            lnkNext.Enabled = Not pagedatasource.IsLastPage
            lnkPrevious.Enabled = Not pagedatasource.IsFirstPage
            ViewState("totpage") = pagedatasource.PageCount
            If pagedatasource.PageCount > 1 Then
                dlstudentdetail.DataSource = pagedatasource
                dlstudentdetail.DataBind()
                Dim dtnew As New DataTable()
                dtnew.Columns.Add("PageIndex")
                dtnew.Columns.Add("PageText")
                FirstIndex = Pageno - 5
                If Pageno > 5 Then
                    LastIndex = Pageno + 5
                    lnkPrevious.Visible = True
                Else
                    LastIndex = 10
                End If
                If LastIndex > Convert.ToInt32(ViewState("totpage")) Then
                    LastIndex = Convert.ToInt32(ViewState("totpage"))
                    FirstIndex = LastIndex - 5
                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
                dlpaging.DataSource = dtnew
                dlpaging.DataBind()
            End If
        Catch ex As Exception
        End Try
    End Sub

Write the code on Next link button click. When users click on this button they move to next page number.
C#:
protected void lnkNext_Click(object sender, EventArgs e)
    {
        lnkNext.Attributes["style"] = "color:#000";      
        lnkPrevious.Attributes["style"] = "";
       
        if (Pageno == totalPages)
        {
            Pageno = totalPages;
        }
        else
        {
            Pageno = Pageno + 1;
        }
        BindDataList();
    }

VB:
Protected Sub lnkNext_Click(sender As Object, e As EventArgs) Handles lnkNext.Click
        lnkNext.Attributes("style") = "color:#000"
        lnkPrevious.Attributes("style") = ""
        If Pageno = totalPages Then
            Pageno = totalPages
        Else
            Pageno = Pageno + 1
        End If
        BindDataList()
    End Sub
Write the code on previous button click. When user clicks on previous button users move to previous page number.
C#:
protected void lnkPrevious_Click(object sender, EventArgs e)
    {
        lnkPrevious.Attributes["style"] = "color:#000";   
        lnkNext.Attributes["style"] = "";
        if (Pageno == 0)
        {
            Pageno = 0;
        }
        else
        {
            Pageno = Pageno - 1;
        }
        BindDataList();
    }

VB:
Protected Sub lnkPrevious_Click(sender As Object, e As EventArgs) Handles lnkPrevious.Click
        lnkPrevious.Attributes("style") = "color:#000"
        lnkNext.Attributes("style") = ""
        If Pageno = 0 Then
            Pageno = 0
        Else
            Pageno = Pageno - 1
        End If
        BindDataList()
    End Sub
After that write code on Datalist itemCommand event.
C#:
protected void dlpaging_ItemCommand(object source, DataListCommandEventArgs e)
    {
            Pageno = Convert.ToInt16(e.CommandArgument.ToString());
            BindDataList();
    }

VB:
Protected Sub dlpaging_ItemCommand(source As Object, e As DataListCommandEventArgs) Handles dlpaging.ItemCommand
        Pageno = Convert.ToInt32(e.CommandArgument.ToString())
        BindDataList()
    End Sub
Write the code on Datalist ItemDataBound event to highlight the selected page number.
C#:
protected void dlpaging_ItemDataBound(object sender, DataListItemEventArgs 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 dlpaging_ItemDataBound(sender As Object, e As DataListItemEventArgs) Handles dlpaging.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

Now build, run the project and check the result.
result:
Implement Google like Custom Pagination in Datalist Control in Asp.net

Download the Code:
Download

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

4 comments:

  1. how can we use query string with this article if i need on click button i get pageindex on url

    ReplyDelete
    Replies
    1. See this article: http://stackoverflow.com/questions/34039504/how-to-configure-the-index-of-a-datalist-in-asp-net
      It may help u to meet your requirement.

      Delete