Skip Navigation

VBScript Pagination

One of the first problems many web developers faces is that of pagination. A database query can sometimes results in hundreds, maybe thousands, of results, and they must all be displayed. Without pagination, those results create a huge, unusable mess for any user.

The problem with any automated pagination script is the preservation of variables. There is no point displaying 10 search results on each page of a result set if a site cannot remember what you searched for from one page to the next. This can one very repetitive part of programming web pages - the preservation of variables.

The following script will work around that problems. There is one downside - you must use querystring variables, rather than form variables (set a form to "GET" rather than "POST"), as otherwise the script will not retain the variables from one page to the next.

Other than that, it is very very simple to use. Simply include it on (for example) a search results page, and call it as normal (replacing current_page with the number of the current page, and total_pages with the total number of pages to display, or the variables holding those pieces of information), and the rest will be done for you.

If you wish to use something other than "current_page" as the variable name for the page number in the querystring, you will also need to change that in the script. The easiest way would be to do a simple find and replace on "current_page", though please do back your work up before doing any 'find and replace' work.

  1. call do_pagination(current_page, total_pages)

The following code is based upon the PHP pagination code used in phpBB, which is probably why the results may look familiar.

  1. function do_pagination(current_page, total_pages)
  2. current_page = cint(current_page)
  3. dim url
  4. dim strPages : strPages = ""
  5. dim intMaxPages
  6. dim intMinPages
  7. dim intPaginI
  8. ' We start be building the URL to add the current_page variable to ... by removing the old current_page data
  9. dim objRegExp : set objRegExp = new RegExp
  10. objRegExp.Pattern = "(&|\?)?current_page=[^&]*(&|$)"
  11. objRegExp.IgnoreCase = true
  12. objRegExp.Global = true
  13. url = objRegExp.replace(request.ServerVariables("SCRIPT_NAME") & "?" & request.ServerVariables("QUERY_STRING"), "$1")
  14. set objRegExp = nothing
  15. if (right(url, 1) = "&") then
  16. url = left(url, len(url)-1)
  17. end if
  18. if (right(url, 1) = "?") then
  19. url = left(url, len(url)-1)
  20. end if
  21. ' Right, now we've got a clean url. Add a character to precede the new current_page value, and off we go!
  22. if (instr(url, "?") > 0) then
  23. url = url & "&"
  24. else
  25. url = url & "?"
  26. end if
  27.  
  28. if (total_pages > 10) then
  29. if (total_pages > 3) then
  30. intMaxPages = 3
  31. else
  32. intMaxPages = total_pages
  33. end if
  34. for intPaginI = 1 to intMaxPages
  35. if (intPaginI = current_page) then
  36. strPages = strPages & "<strong>" & intPaginI & "</strong>"
  37. else
  38. strPages = strPages & "<a href=""" & url & "current_page=" & intPaginI & """>" & intPaginI & "</a>"
  39. end if
  40. if (intPaginI < intMaxPages) then
  41. strPages = strPages & ", "
  42. end if
  43. next
  44. if (total_pages > 3) then
  45. if ((current_page > 1) and (current_page < total_pages)) then
  46. if (current_page > 5) then
  47. strPages = strPages & " ... "
  48. else
  49. strPages = strPages & ", "
  50. end if
  51. if (current_page > 4) then
  52. intMinPages = current_page
  53. else
  54. intMinPages = 5
  55. end if
  56. if (current_page < total_pages - 4) then
  57. intMaxPages = current_page
  58. else
  59. intMaxPages = total_pages - 4
  60. end if
  61. for intPaginI = intMinPages - 1 to intMaxPages + 1
  62. if (intPaginI = current_page) then
  63. strPages = strPages & "<strong>" & intPaginI & "</strong>"
  64. else
  65. strPages = strPages & "<a href=""" & url & "current_page=" & intPaginI & """>" & intPaginI & "</a>"
  66. end if
  67. if (intPaginI < intMaxPages + 1) then
  68. strPages = strPages & ", "
  69. end if
  70. next
  71. if (current_page < total_pages - 4) then
  72. strPages = strPages & " ... "
  73. else
  74. strPages = strPages & ", "
  75. end if
  76. else
  77. strPages = strPages & " ... "
  78. end if
  79. for intPaginI = total_pages - 2 to total_pages
  80. if (intPaginI = current_page) then
  81. strPages = strPages & "<strong>" & intPaginI & "</strong>"
  82. else
  83. strPages = strPages & "<a href=""" & url & "current_page=" & intPaginI & """>" & intPaginI & "</a>"
  84. end if
  85. if (intPaginI < total_pages) then
  86. strPages = strPages & ", "
  87. end if
  88. next
  89. end if
  90. else
  91. for intPaginI = 1 to total_pages
  92. if (intPaginI = current_page) then
  93. strPages = strPages & "<strong>" & intPaginI & "</strong>"
  94. else
  95. strPages = strPages & "<a href=""" & url & "current_page=" & intPaginI & """>" & intPaginI & "</a>"
  96. end if
  97. if (intPaginI < total_pages) then
  98. strPages = strPages & ", "
  99. end if
  100. next
  101. end if
  102. do_pagination = strPages
  103. end function

14 comments

Drago
United States #1: November 1, 2006
Could you explain a little better an example of how to use it?
Drago i dont think the man should show you how to go to bathroom. He already show you how actually can paginate records in ASP. If you are a bedroom programmer like many others, I suggest you to try something else.
MANDALAY
Unknown #3: May 16, 2007
You suck dude.....its really disgusting the way u write this code...man you are just a baby...
Thanks for the intelligent, constructive criticism, Mandalay. Always nice to see smart people contributing.
Great example, Dave. Thank you so much.

As for MANDALAY, grow up.
Varun Reddy
India #6: September 27, 2007
<%@ Language="VBScript" EnableSessionState="True" %>
<% Option Explicit
server.ScriptTimeout=1000
Response.Buffer = True

%>
<!-- #include file="DbConMain.inc" -->
<%
Dim db
db=request.querystring("src")

if db="NIC" then
openCNMain
end if
if db <> "NIC" then
Response.Redirect("default.asp")
end if
%>
<html>
<head>
<meta name="VI60_defaultClientScript" content="VBScript">
<title>Invoice Creation</title>
<META http-equiv=Content-Type content="text/html; charset=windows-1252">
<META content=noindex,nofollow name=robots><LINK href="IEstyle.css" type=text/css rel=stylesheet>
<link href="IMAGES/stylesheet.css" rel="stylesheet" type="text/css">
<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
<LINK REL="stylesheet" type="text/css" href="im/popcalendar.css" />
<script language="JavaScript" src="tigra_tables.js"></script>
<script language="javascript" type="text/javascript">
function submitt(thisform)
{
var invID = window.document.frm1.invoiceID.value;
if (invID == "")
{
alert("Please Enter Invoice Number");
window.document.frm1.invoiceID.focus();
return false;
}
else if(isNaN(invID))
{
alert("Invalid Entry, Only Numeric Values are Allowed!..");
window.document.frm1.invoiceID.focus();
return false;
}
else
{
return true;
}
}
</script>
</head>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<table width="1100" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="38" rowspan="5" align="left" valign="top" bgcolor="#E4E4E4"></td>
<td width="929" height="26" align="left" valign="top" bgcolor="#E4E4E4"></td>
<td width="38" rowspan="5" align="left" valign="top" bgcolor="#E4E4E4"></td>
</tr>
<tr>
<td height="24"></td>
</tr>
<tr>
<td><table width="927" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="24" rowspan="3" align="left" valign="top"></td>
<td><table width="975" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="11"><img src="images/top_bar_lf.gif" width="11" height="102" /></td>
<td width="980" align="left" valign="middle" background="images/top_bar_mid.gif"><table width="854" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="236" align="left" valign="middle">
<a href="default.asp"><img src="images/logo.jpg" width="236" height="59" title="Home Page" border="0" /></a></td>
<td width="435" align="right" valign="middle"><table width="400" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="385" class="nTextB" >
<font color="#294B5F" >Invoice Creation</font></td>
</tr>
</table></td>
<td width="183" align="left" valign="top"><table width="183" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
</tr>
<tr>
<td><table width="183" border="0" cellspacing="2" cellpadding="2">
<tr>
<td >&nbsp;</td>
</tr>
</table></td>
</tr>
</table></td>
</tr>
</table></td>
<td width="11"><img src="images/top_bar_rg.gif" width="11" height="102" /></td>
</tr>
</table></td>
<td width="24" rowspan="3" align="left" valign="top"></td>
</tr>
<tr>
<td>&nbsp;</td>
</tr>
<tr>
<td width="100%" height="359" align="left" valign="top">
<!-- #include file="headerAdmin.asp" -->
<br>
<br>
<br>
<form name="frm1" method="post" onSubmit="return submitt(this);" action="dsp_view_delete_invoice.asp?src=NIC">
<table border="0" width="100%">
<tr>
<td width="69%">&nbsp;</td>
<td width="20%" align="center">
<font color="#294B5F" face="Verdana" size="2">
<%
if Request.QueryString("Msg") <> "" then
Response.Write("<strong>No Records To Display</strong>")
end if
%>
</font>
</td>
<td>&nbsp;</td>
</tr>
<tr>
<td align="right" colspan="2">
<font face="Verdana" size="2"><strong>Enter Invoice Number</strong></font>&nbsp;&nbsp;
<input name="invoiceID" type="text" class="txt" title="Enter Invoice Number" tabindex="1">
</td>
<td width="11%">
<input type="submit" name="Submit Invoice Number" value="Go" title="Go" class="btnStyle" tabindex="2"/>
</td>
</tr>
</table>
</form>
<table cellpadding="2" cellspacing="2" align="center" width="95%">
<tr>
<td colspan="6" align="center">
<font color="#294B5F" face="Verdana" size="2">
<%
if Request.QueryString("Del") <> "" then
Response.Write("<strong>Record Deleted Successfully</strong>")
end if
%>
</font>
</td>
</tr>
<tr>
<td colspan="6">&nbsp;</td>
</tr>
</table>
<table cellpadding="2" cellspacing="2" align="center" width="95%" id="Invoice Details">
<tr bgcolor="#e4e4e4" height="25" class="nTextH">
<th nowrap>Invoice Id</th>
<th nowrap>Program</th>
<th nowrap>Module</th>
<th nowrap>Create Date</th>
<th nowrap>From Date</th>
<th nowrap>To Date</th>
</tr>
<%
dim rsInvoice,qryInvoice

set rsInvoice=Server.CreateObject("ADODB.RecordSet")
qryInvoice="SELECT invoice_Details.invoiceID, Portfolio.portfolioName, Program.programName, Project.projectName,ModuleList.moduleName, invoice_Details.createdate, invoice_Details.fromDate, invoice_Details.toDate, invoice_Details.toAddress FROM (Program INNER JOIN (Project INNER JOIN (invoice_Details INNER JOIN ModuleList ON invoice_Details.moduleID = ModuleList.moduleID) ON Project.projectID = ModuleList.projectID) ON Program.programID = Project.programID) INNER JOIN Portfolio ON Program.portfolioID = Portfolio.portfolioID ORDER BY invoice_Details.invoiceID"


Dim thisPage, rowcount, TotalPages, pgSise, RecCount
Const adOpenStatic = 3
thisPage = Trim(Request("thisPage"))
if thisPage = "" then thisPage = 1

rsInvoice.CursorType = adOpenStatic
rsInvoice.PageSize = 10
rsInvoice.Open qryInvoice,con,1,3
if not rsInvoice.EOF then
rsInvoice.AbsolutePage = cINT(thisPage)
end if
TotalPages = rsInvoice.PageCount
pgSise = rsInvoice.PageSize
RecCount = rsInvoice.RecordCount

'Response.Write(TotalPages&"<br>")
rowCount = 0

If Not rsInvoice.EOF then
Do While Not rsInvoice.EOF and rowCount < pgSise
%>
<tr>
<td nowrap class='nText'>
<a href="dsp_view_delete_invoice.asp?src=NIC&invoiceID=<%=rsInvoice(0)%>&val=List&thisPage=<%=thisPage%>" class="namelink" title="Click Here To View Detailed Invoice Details"><%=rsInvoice(0)%></a>
</td>
<td nowrap class='nTextL'>&nbsp;<%=rsInvoice(2)%></td>
<td nowrap class='nTextL'>&nbsp;<%=rsInvoice(4)%></td>
<td nowrap class='nText'>
<%=DatePart("d",rsInvoice(5))%>-<%=monthname(DatePart("m",rsInvoice(5)),true)%>-<%=DatePart("yyyy",rsInvoice(5))%>
</td>
<td nowrap class='nText'>
<%=DatePart("d",rsInvoice(6))%>-<%=monthname(DatePart("m",rsInvoice(6)),true)%>-<%=DatePart("yyyy",rsInvoice(6))%>
</td>
<td nowrap class='nText'>
<%=DatePart("d",rsInvoice(7))%>-<%=monthname(DatePart("m",rsInvoice(7)),true)%>-<%=DatePart("yyyy",rsInvoice(7))%>
</td>
</tr>
<%
rsInvoice.movenext
rowCount = rowCount + 1
Loop
else
%>
<tr>
<td colspan="6" align="center">
<font color="#800000" face="Verdana" size="2"><b>Sorry ! No Records To Display</b></font>
</td>
</tr>
<%
end if
%>

</table>
<script language="JavaScript">
<!--
tigra_tables('Invoice Details', 1, 0, '#e5e5e5', '#F9F9F9', '#ffccff', '#cc99ff');
// -->
</script>
<%
If TotalPages > 1 then
CALL Pagination(thisPage, TotalPages)
End if
%>
<%
Function Pagination(thisPage, TotalPages)

thisPage = cint(thisPage)
Dim url, MaxPages, MinPages, CurrPage, vUrl
Dim strPages : strPages = ""

vUrl = "invoice_list.asp?src=NIC&"

IF (TotalPages > 10) THEN 'Main IF
if (TotalPages > 3) then
MaxPages = 3
else
MaxPages = TotalPages
end if

for CurrPage = 1 to MaxPages
if (CurrPage = thisPage) then
strPages = strPages & "<font face=Verdana size=2px; color=#C00221><strong>"&CurrPage&"</strong></font>"
else
strPages = strPages & "<a href="&vUrl&"thisPage="&CurrPage&" class=namelink>"&CurrPage&"</a>"
end if
if (CurrPage < MaxPages) then
strPages = strPages & "&nbsp;&nbsp;"
end if
next

if (TotalPages > 3) then 'If Sub if 1
if ((thisPage > 1) and (thisPage < TotalPages)) then 'If Sub if 2
if (thisPage > 5) then
strPages = strPages & " . . . "
else
strPages = strPages & "&nbsp;&nbsp;"
end if

if (thisPage > 4) then
MinPages = thisPage
else
MinPages = 5
end if

if (thisPage < TotalPages - 4) then
MaxPages = thisPage
else
MaxPages = TotalPages - 4
end if

for CurrPage = MinPages - 1 to MaxPages + 1
if (CurrPage = thisPage) then
strPages = strPages & "<font face=Verdana size=2px; color=#C00221><strong>"&CurrPage&"</strong></font>"
else
strPages = strPages & "<a href="&vUrl&"thisPage="&CurrPage&" class=namelink>"&CurrPage&"</a>"
end if
if (CurrPage < MaxPages + 1) then
strPages = strPages & "&nbsp;&nbsp;"
end if
next

if (thisPage < TotalPages - 4) then
strPages = strPages & " . . . "
else
strPages = strPages & "&nbsp;&nbsp;"
end if
else
strPages = strPages & " . . . "
end if 'End If Sub if 2

for CurrPage = TotalPages - 2 to TotalPages
if (CurrPage = thisPage) then
strPages = strPages & "<font face=Verdana size=2px; color=#C00221><strong>"&CurrPage&"</strong></font>"
else
strPages = strPages & "<a href="&vUrl&"thisPage="&CurrPage&" class=namelink>"&CurrPage&"</a>"
end if
if (CurrPage < TotalPages) then
strPages = strPages & "&nbsp;&nbsp;"
end if
next
end if 'End If Sub IF 1
else
for CurrPage = 1 to TotalPages
if (CurrPage = thisPage) then
strPages = strPages & "<font face=Verdana size=2px; color=#C00221><strong>"&CurrPage&"</strong></font>"
else
strPages = strPages & "<a href="&vUrl&"thisPage="&CurrPage&" class=namelink>"&CurrPage&"</a>"
end if

if (CurrPage < TotalPages) then
strPages = strPages & "&nbsp;&nbsp;"
end if
next
End IF 'Mail End IF

Pagination = strPages

Dim DecthisPage,IncthisPage
DecthisPage = thisPage - 1
IncthisPage = thisPage + 1

'Response.Write(DecthisPage&"<br>")
'Response.Write(thisPage&"<br>")
'Response.Write(IncthisPage&"<br>")
Response.Write("<table cellpadding=2 cellspacing=2 align=center width=95% border=0>")
Response.Write("<tr>")
Response.Write("<td>")
Response.Write("&nbsp;")
Response.Write("</td>")
Response.Write("</tr>")
Response.Write("<tr>")
Response.Write("<td colspan=6 align=center>")
if thisPage > 1 then
Response.Write("<a href="&vUrl&"thisPage="&DecthisPage&" class=namelink>Previous</a>&nbsp;&nbsp;&nbsp;")
end if
Response.Write(Pagination)
if IncthisPage <= TotalPages then
Response.Write("&nbsp;&nbsp;&nbsp;<a href="&vUrl&"thisPage="&IncthisPage&" class=namelink>Next&nbsp;</a>")
end if
Response.Write("</td>")
Response.Write("</tr>")
Response.Write("</table>")

End Function
%>

&nbsp;<!---->
</td>
</tr>

</table></td>
</tr>
<tr>
<td height="24"></td>
</tr>
<tr>
<td height="38" align="center" valign="middle" bgcolor="#E4E4E4" class="top-txt">&copy; Copyright Celunite Inc. 2006-<%=year(now)%></td>
</tr>
</table>

<%


rsInvoice.Close
Set rsInvoice = Nothing
con.Close
%>
</body>
</html>
Varun Reddy
India #7: September 27, 2007
and the DbConMain.inc includes

<object progid="adodb.connection" id=con runat=server></object>
<script Language=VBScript RunAt=Server>

Sub openCNMain

con.Provider = "Microsoft.jet.oledb.4.0"
'response.write con.State
If con.State=1 Then con.close
con.Open server.MapPath( "final.mdb")

End Sub

Sub closeCNMain
If con.State=1 Then
con.close
set con = Nothing
end if
End Sub

</script>
Varun Reddy
India #8: September 27, 2007
Use this for Pagination. I made necessary modifications so that every one can use it.
Shawson
United Kingdom #9: February 19, 2008
Cheers Dave, once more you have removed a little pain from my day- i recall seeing this function years back on a site of yours i worked at back at the egg- was hoping it would appear on here somewhere!
Jason
United Kingdom #10: February 21, 2008
Ahh Frontpage *runs far away*

<meta name="GENERATOR" content="Microsoft FrontPage 4.0">
i worked on ur code. everything worked right.
But my whole data(1387 rows) is displaying only on the 1st page.

help me!

Thanx in advance
Thank you for the code, and not only the code but also your clearity. I've seen many codes just completely unclear and unclean, not properly spaced and hard to read, but yours is very easy to read and easily implemented.

One suggestion would be to put comments in the code so that developers like myself can easily make changes if need be
dave too (II)
United States #13: December 13, 2008
hey DC --

spanks again for a great chunk of coding goodness. This pager + plus your date formatting code has saved my sorry azz several hours, yet again! ( date functs here: http://www.addedbytes.com/asp/vbscript-date-format-functions/ )

spanks a mill, dave-y doo! 1st Jack & coke's on me if we ever meet up, mate.
d
Mandalay may have put it in an ignorant manner, but he was correct - that code is sloppy as hell. I'd like to round up all the sloppy web developers and punch them in the face, one by one.

Post Your Comment

· Comments with keywords instead of a name have their URLs removed.
· Your email address will not be displayed or shared.

Live Comment Preview

 United States #15: 1 minute ago