萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 將 Recordset 以 N 列表格輸出的通用函式

需求場景

將資料庫查詢結果以固定欄數 (如 4 欄) 的 HTML 表格呈現,常用於商品目錄、圖片牆、會員名冊等。

通用函式

Function RenderRecordsetAsTable(rs, cols, fields, Optional emptyCellHtml = " ")
  ' rs: 已開啟的 Recordset (游標型態建議 adOpenStatic + adLockReadOnly)
  ' cols: 每列欄數 (Integer)
  ' fields: 要顯示的欄位名陣列 或 逗號分隔字串
  ' emptyCellHtml: 最後一列不足時填充的 HTML

  Dim arrFields, fieldCount, total, rendered, i, colIdx, html
  If IsArray(fields) Then
    arrFields = fields
  Else
    arrFields = Split(fields, ",")
  End If
  fieldCount = UBound(arrFields) + 1

  ' 先取得總筆數 (支援不支援 RecordCount 的游標)
  On Error Resume Next
  total = rs.RecordCount
  If Err.Number <> 0 Or total = -1 Then
    rs.MoveLast: rs.MoveFirst
    total = rs.RecordCount
  End If
  On Error GoTo 0

  If total = 0 Then
    RenderRecordsetAsTable = "

無資料

" Exit Function End If html = "" & vbCrLf rendered = 0 colIdx = 0 html = html & "" & vbCrLf Do Until rs.EOF html = html & "" & vbCrLf rendered = rendered + 1 colIdx = colIdx + 1 If colIdx = cols Then If rendered < total Then html = html & "" & vbCrLf Else html = html & "" & vbCrLf End If colIdx = 0 End If rs.MoveNext Loop ' 補齊最後一列 If colIdx > 0 Then For i = colIdx To cols - 1 html = html & "" & vbCrLf Next html = html & "" & vbCrLf End If html = html & "
" For i = 0 To fieldCount - 1 html = html & rs(arrFields(i)) If i < fieldCount - 1 Then html = html & "
" Next html = html & "
" & emptyCellHtml & "
" RenderRecordsetAsTable = html End Function

使用範例

<%
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=SQLOLEDB;Data Source=.;Initial Catalog=Northwind;Integrated Security=SSPI"
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open "SELECT CustomerID, CompanyName, ContactName, City FROM Customers", conn, 3, 1 ' adOpenStatic, adLockReadOnly

Response.Write RenderRecordsetAsTable(rs, 4, "CustomerID,CompanyName,ContactName,City")

rs.Close: Set rs = Nothing
conn.Close: Set conn = Nothing
%>

進階擴充

  • 支援自訂儲存格樣板:傳入回呼函式 cellRenderer(rs, fieldName)。
  • 加入表頭列:<th> 迴圈輸出欄位標題。
  • 搭配 CSS Class 實現 RWD:table class="grid" + @media 調整欄數。
copyright © 萬盛學電腦網 all rights reserved