我正在开发一个遗留的ASP.NET 2.0 Web Forms网站。由于某些原因,DataReader控件没有获取SQL查询所拉取的所有记录。我在SQL Management Studio中运行查询,返回了3条记录。当我手动迭代DataReader时,我只得到2条记录,当我数据绑定到中继器时,只显示2条记录。
VB.NET代码:
sql = "SELECT tblImages.ImageID, tblProducts.ProductName FROM tblImages INNER JOIN tblProducts ON tblImages.ProductID = tblProducts.ProductID WHERE tblImages.ProductID = 725 ORDER BY tblImages.Main DESC, tblImages.ImageID ASC"
comm = New SqlCommand(sql, conn)
dr = comm.ExecuteReader()
If dr.Read() = True Then
rptGallery.DataSource = dr
rptGallery.DataBind()
End If
dr.Close()
conn.Close()
中继器标记:
<asp:Repeater ID="rptGallery" runat="server">
<HeaderTemplate>
<div id="slider" class="flexslider">
<ul class="slides">
</HeaderTemplate>
<ItemTemplate>
<li>
<a href="getimage.aspx?id=<%# Eval("ImageID")%>&format=large" data-featherlight="image">
<img src="getimage.aspx?id=<%# Eval("ImageID")%>&format=medium" alt="<%# Eval("ProductName")%>" /></a>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</div>
</FooterTemplate>
</asp:Repeater>
当我按照下面的代码进行手动迭代时,我可以检查变量ic,在迭代数据读取器中的记录后,它的值是2,而它应该是3。
If dr.Read() = True Then
Dim ic As Integer = 0
While dr.Read()
ic = ic + 1
End While
End If
每次调用dr.Read()
都会使光标前进。所以你跳过了一张唱片。也许您应该使用DataTable而不是读取记录?只需使用Load()
函数从数据读取器读取信息,然后将其绑定到中继器即可。
此外,您需要将SqlConnection
封装在using语句中,以确保它得到正确处理。
在C#中是这样的:
sql = "SELECT tblImages.ImageID, tblProducts.ProductName FROM tblImages INNER JOIN tblProducts ON tblImages.ProductID = tblProducts.ProductID WHERE tblImages.ProductID = 725 ORDER BY tblImages.Main DESC, tblImages.ImageID ASC";
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection("connectionstring"))
{
comm = new SqlCommand(sql, conn);
conn.Open();
dt.Load(comm.ExecuteReader());
}
rptGallery.DataSource = dt;
rptGallery.DataBind();
在VB.NET中是这样的(自动代码转换器,因为我不是VB编码器)
sql = "SELECT tblImages.ImageID, tblProducts.ProductName FROM tblImages INNER JOIN tblProducts ON tblImages.ProductID = tblProducts.ProductID WHERE tblImages.ProductID = 725 ORDER BY tblImages.Main DESC, tblImages.ImageID ASC"
Dim dt As New DataTable()
Using conn As New SqlConnection("connectionstring")
comm = New SqlCommand(sql, conn)
conn.Open()
dt.Load(comm.ExecuteReader())
End Using
rptGallery.DataSource = dt
rptGallery.DataBind()