我有一个带有简单html表的经典ASP页面,我想基于从数据库中提取的未知数量的记录来循环表行,但是,当我使用do / while循环循环记录时,我收到一个错误,说BOF或EOF是真的。我希望表中的每一行都交替使用背景颜色(我在CSS中设置的颜色)。
<% do while not rsTest.eof %>
<tr class="odd">
<td colspan="5"><%=(rsTest.Fields.Item("field").Value)%></td>
</tr>
<% rsTest.moveNext
if not rsTest.eof then
count = count + 1 %>
<tr class="even">
<td colspan="5"><%=(rsTest.Fields.Item("field").Value)%></td>
</tr>
<% end if %>
<% count = count + 1
rsTest.moveNext
loop %>
根据浏览器,错误发生在循环之前的最后一个“rsRoster.moveNext”上。如果从数据库中提取了偶数个记录,则循环不会出错,但如果拉出奇数量的记录则会出错。我已经尝试插入一些“如果EOF然后没有,否则执行代码”,但代码检查EOF似乎是在我这样做时似乎被忽略了。任何建议将不胜感激。
答案 0 :(得分:3)
我知道我在这个上生锈了,但试试这个:
<%
Dim oddFlag
oddFlag = 1
do while not rsTest.eof
if oddFlag=1 Then
oddFlag=0
Response.write("<tr class='odd'>")
Response.write("<td colspan='5'>")
Response.write(rsTest.Fields.Item("field").Value)
Response.write("</td></tr>")
else
oddFlag=1
Response.write("<tr class='even'>")
Response.write("<td colspan='5'>")
Response.write(rsTest.Fields.Item("field").Value)
Response.write("</td></tr>")
end if
rsTest.moveNext
loop
%>
答案 1 :(得分:2)
由于其他答案没有提到这一点:你的代码的问题是你正在做两次MoveNext,而第二个没有测试第一个是否已经达到EOF。
无论如何,这是一种不必要的复杂的交替颜色方式。
dim i, rs
'... database stuff, table header, etc.
i = 0
Do Until rs.EOF
i = i + 1
Response.Write "<tr class='"
If i Mod 2 = 0 Then Response.Write "even" Else Response.Write "odd" End If
Response.Write "'>"
'... write out the actual content of the table
Response.Write "</tr>"
rs.Movenext
Loop
'... clean up database, close table
使用此方法,您的计数器变量(i
)可用作实际的计数器 - 例如,如果您要写出“返回的行数”最后的消息,你可以。
答案 2 :(得分:1)
这里有点马虎,但这就是我通常会做到的事情:
<%
Dim i
i = 1
do while not rsTest.eof
If i = 1 Then %>
<tr class="odd">
<% Else %>
<tr class="even">
<% End If %>
<td colspan="5"><%=(rsTest.Fields.Item("field").Value)%></td>
</tr>
<%
i = i + 1
If i = 3 Then i = 1
count = count + 1
rsTest.moveNext
loop %>
答案 3 :(得分:1)
为什么不使用:
While not rs.EOF
'stuff
rs.movenext
wend
或确保:
if not rs.eof then
while not rs.eof
'stuff
rs.movenext
wend
end if
更好的方法是缓存每一个并保持连接非常短:
'... set global base (include file)
dim dbcon, rs, rsSQL, rsArray
Function openCon()
set dbcon = server.createobject("ADODB.Connection")
dbcon.open Application("YOURDB_Connectionstring")
End Function
Function closeCon()
dbcon.Close
set dbcon = nothing
End Function
function rw(stringwriteshortcut)
response.write(stringwriteshortcut)
end function
'... end global
'... Database interaction:
rsSQL = "SELECT item1, item2 FROM table where ID = 1"
openCon()
set rs = dbcon.execute(rsSQL)
if not rs.eof then
rsArray = rs.getRows();
end if
closeCon()
dim items
if isarray(rsArray) then
for items = 0 to UBound(rsArray, 2)
rw(rsArray(0,items) &"<br>")
rw(rsArray(1,items) &"<br>")
next
else
rw("nothing there")
end if