分頁是資料列表頁面核心功能。本文提供一個即拿即用的 PageControl Sub 程序,內建 CSS 樣式、自動保留原查詢參數、智慧省略號 (最多顯示 7 個頁碼)、首尾頁永遠顯示,適合任意 ASP 專案直接引用。
<%
' PageControl 分頁副程式
' 參數:iCount=總筆數, pageCount=總頁數, page=目前頁碼
Sub PageControl(iCount, pageCount, page)
' 1. 內嵌 CSS (可外移至 .css)
Response.Write "" & chr(13)
' 2. 重建查詢字串 (排除 page 參數)
Dim query, a, x, temp, action
action = "https://" & Request.ServerVariables("HTTP_HOST") & Request.ServerVariables("SCRIPT_NAME")
query = Split(Request.ServerVariables("QUERY_STRING"), "&")
For Each x In query
a = Split(x, "=")
If StrComp(a(0), "page", vbTextCompare) <> 0 Then
temp = temp & a(0) & "=" & a(1) & "&"
End If
Next
' 3. 輸出分頁 HTML
Response.Write "" & chr(13)
Response.Write "" & page & "/" & pageCount & "頁" & chr(13)
Response.Write "共" & iCount & "筆記錄" & chr(13)
If pageCount <= 6 Then
' 總頁數 ≤ 6:全部顯示
For xl = 1 To pageCount
If page = xl Then
Response.Write "" & xl & "" & chr(13)
Else
Response.Write "" & xl & " " & chr(13)
End If
Next
Else
' 總頁數 > 6:智慧省略號
' 首頁
If page = 1 Then
Response.Write "1" & chr(13)
Else
Response.Write "1 " & chr(13)
End If
' 左省略號
If page > 4 Then Response.Write "..." & chr(13)
' 中間連續頁碼
Dim i1, i2
If page < 5 Then i1 = 1 Else i1 = page - 2
If page > (pageCount - 4) Then i2 = pageCount Else i2 = page + 3
For xll = i1 To i2
If xll <> 1 And xll <> pageCount Then
If xll = page Then
Response.Write "" & xll & "" & chr(13)
Else
Response.Write "" & xll & " " & chr(13)
End If
End If
Next
' 右省略號
If page < (pageCount - 4) Then Response.Write "..." & chr(13)
' 尾頁
If page = pageCount Then
Response.Write "" & pageCount & "" & chr(13)
Else
Response.Write "" & pageCount & " " & chr(13)
End If
End If
Response.Write "" & chr(13)
End Sub
%>
<!-- #include file="pageControl.asp" -->
<%
' 假設已查詢總筆數 rsCount,每頁 20 筆
pageSize = 20
pageCount = Int((rsCount + pageSize - 1) / pageSize) ' 總頁數
currentPage = CInt(Request.QueryString("page"))
If currentPage < 1 Then currentPage = 1
If currentPage > pageCount Then currentPage = pageCount
' 查詢當頁資料 (SQL Server TOP + NOT IN 或 ROW_NUMBER)
sql = "SELECT * FROM (SELECT TOP " & pageSize & " * FROM (SELECT TOP " & (currentPage * pageSize) & " * FROM News ORDER BY ID DESC) ORDER BY ID ASC)"
' ... 執行查詢輸出資料列表 ...
' 呼叫分頁
Call PageControl(rsCount, pageCount, currentPage)
%>

action 與連結產生邏輯。ROW_NUMBER() 分頁,避免雙重 TOP 效能問題。