我正在使用传统的ASP.NET 2.0 Web窗体站点。由于某种原因,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,并且在迭代通过datareader中的记录后它的值是2,它应该是3。
If dr.Read() = True Then
Dim ic As Integer = 0
While dr.Read()
ic = ic + 1
End While
End If
答案 0 :(得分:1)
每次调用dr.Read()
都会使光标前进。所以你要跳过一条记录。也许您应该使用DataTable而不是阅读记录?只需使用Load()
函数从数据读取器中读取信息,然后将其绑定到转发器。
此外,您需要将SqlConnection
包裹在using statement中以确保其得到妥善处理。
在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()