Read, With the Name of Your Lord Who Created

Pagination in ASP.NET

Posted by triaslama on May 18, 2008

ASP.NET has DataGrid control, and datagrid control has build in support for pagination. What I do in this post is just something like datagrid pagination, but I add two buttons each of them to navigate to previous and next page respectively.

I use ListOfPage class to produce list of page number, you can see more on this class in my previous post here. For simplicity I use array of string as data source, in more common scenario maybe we use data from database, represent it in DataTable then use the DataTable as a data source.

I do the manual pagination in ASP.NET with code behind style. There is I put the code that produce list of page in a separate file (I named it ManualPagination.aspx.cs). The presentation page laid in ManualPagination.aspx which refers to our code behind file.

Let’s start with presentation page! It’s quite simple, this is the source code (ManualPagination.aspx):

    <%@ Page Language=”C#” CodeFile=”ManualPagination.aspx.cs” Inherits=”ManualPagination.CodeBehindClass” %><html>
    <head>
    <title>Manual Pagination in ASP.NET</title>
    <style type=”text/css”>
    .clr
    {
    background-color:lightblue;
    }
    </style>
    </head>
    <body>
    <form runat=”server”>
    <asp:Label id=”lblPresentation” runat=”server” />
    <p />
    <asp:Button id=”btnPrev” text=”Prev” onclick=”btnPrev_Click” runat=”server” />

    <asp:Label id=”lblPages” runat=”server” />

    <asp:Button id=”btnNext” text=”Next” onclick=”btnNext_Click” runat=”server” />
    </form>
    </body>
    </html>

 

One of the important portion of our presentation page relies on the following code:


<%@ Page Language="C#" CodeFile="ManualPagination.aspx.cs" Inherits="ManualPagination.CodeBehindClass" %>

In the above line of code we tell that our presentation page use ManualPagination.CodeBehindClass that resides in ManualPagination.aspx.cs. Here is the code behind (ManualPagination.aspx.cs):

using System;
using System.Web;
using System.Web.UI;
using PageNumbersGenerator;

namespace ManualPagination
{
	public partial class CodeBehindClass : Page
	{
		private ListOfPage lop = new ListOfPage();
		private string[] arrStr;
		private int[] pages;
		int currentPage = 1;
		private int totalPages;

		protected void Page_Load(object sender, EventArgs e)
		{
			DrawPresentation();
			DrawPages();
		}

		private void DrawPresentation()
		{
			arrStr = new string[100];
		    for (int j=startIndex; (j<arrStr.Length) && 
                          (j<startIndex+rowsPerPage); j++)
			{
				if (j%2==0)
					str+= "<tr class='clr' >";
				else
					str += "<tr>";
		str+="<td style='border:1px solid red;' >"+arrStr[j]+"</td>";
		str+="</tr>";
			}
			str += "</table>";

			this.lblPresentation.Text = str;
		}

		private void DrawPages()
		{
			string strPages = string.Empty;
			for (int k=0;k<pages.Length;k++) {
                     //replace the 'href' with your own
                     strPages += " <a href='localhost/manualpagination.aspx?
                               page="+pages[k]+"'>"+pages[k]+"</a> ";
			}

			this.lblPages.Text = strPages;
		}

		protected void btnPrev_Click(object sender, EventArgs e)
		{
			int prevPage;
			if (currentPage<=1) {
				prevPage=currentPage;
			}
			else {
				prevPage = currentPage - 1;
			}
                        //replace the location with your own
	                Page.Response.Redirect("localhost/manualpagination.aspx?
                                                page="+prevPage);
		}

		protected void btnNext_Click(object sender, EventArgs e)
		{
			int nextPage;
			if (currentPage>=totalPages) {
				nextPage=currentPage;
			}
			else {
				nextPage = currentPage + 1;
			}
                        // replace the location with your own
	                Page.Response.Redirect("localhost/manualpagination.aspx?
                                                page="+nextPage);
		}
	}
}

 

Let’s dig inside the code behind. I use ListOfPage class to produce page numbers, please go here for more information. I also set the currentPage to 1 (that means we start from page one).

Inside Page_Load() I call these two methods: DrawPresentation() and DrawPages(). Page_Load() called every time our page is loads.

protected void Page_Load(object sender, EventArgs e)
{
DrawPresentation();
DrawPages();
}

Inside DrawPresentation() I draw the table with array of string inside it as data source.


str += "<table style='border:2px solid black;'>";
for (int j=startIndex; (j<arrStr.Length) && (j<startIndex+rowsPerPage); j++)
{
   if (j%2==0)
      str+= "<tr class='clr' >";
   else
      str += "<tr>";
   str+="<td style='border:1px solid red;' >"+arrStr[j]+"</td>";
   str+="</tr>";
}
str += "</table>";

Don’t forget to get the new currentPage every time we inside DrawPresentation() method. We get the new current page from query string as depicted by following code:


if(Page.Request.QueryString["page"]!=null&&Page.Request.QueryString["page"]!=string.Empty)
          currentPage = Convert.ToInt32(Page.Request.QueryString["page"]);

If you want to know how to get query string values in ASP.NET, read my previous post here.

Inside DrawPages() method we just show the list of page produced by ListOfPage class with one more action: we add a hyperlink to every number.


private void DrawPages()
{
   string strPages = string.Empty;
   for (int k=0;k<pages.Length;k++) {
      strPages += " <a href='/postings/pagination/manualpagination.aspx?page="+pages[k]+"'   >"+pages[k]+"</a> ";
   }

this.lblPages.Text = strPages;
}

As a resume we need the following steps to run the code:

  1. Compile ListOfPage class as a library and put it in your bin directory.
  2. In the code behind don’t forget using PageNumbersGenerator; because we are using ListOfPage class that resides in PageNumbersGenerator namespace.
  3. Put ManualPagination.aspx.cs and ManualPagination.aspx in your virtual directory.

Then run it, you should get the result something similar like this:

pagination

ManualPagination.aspx page.

Click ‘Prev’ button to go to previous page and ‘Next’ button to go to next page. Or we can use the list of page numbers to go to a specified page.

I think Its possible to convert the code in Javascript and HTML so we can do the pagination fully in client side. I hope I can do this!

See you next time…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: