【发布时间】:2012-11-25 16:24:06
【问题描述】:
我正在尝试使用 C#.net 从数据库中提取数据并使用 Foreach 循环使其在页面上可见。每次我运行代码时,当我知道数据库中至少有 7 个项目时,我只会显示一个项目。我已经为 C# 放置了下面的代码。
SqlConnection oConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["HomeGrownEnergyConnectionString"].ToString());
string sqlEnergy = "Select * from Product p where p.ProductTypeId=3";
SqlCommand oCmd = new SqlCommand(sqlEnergy, oConnection);
DataTable dtenergy = new DataTable();
SqlDataAdapter oDa = new SqlDataAdapter(oCmd);
try
{
oConnection.Open(); ;
oDa.Fill(dtenergy);
}
catch (Exception ex)
{
lblnodata.Text = ex.Message;
return;
}
finally
{
oConnection.Close();
}
DataTableReader results = dtenergy.CreateDataReader();
if (results.HasRows)
{
results.Read();
foreach(DataRow result in dtenergy.Rows)
{
byte[] imgProd = result["ThumnailLocation"] as byte[];
ID.Text = result["ProductID"].ToString();
Name.Text = result["Name"].ToString();
price.Text = FormatPriceColumn(result["Price"].ToString());
}
}
这是 asp.net 的代码。
<div>
<asp:Image ID="imgProd" CssClass="ProdImg" runat="server" />
<asp:Label runat="server" ID="ID" />
<asp:Label runat="server" ID="Name" />
<asp:Label runat="server" ID="price" />
<asp:TextBox ID="txtQty" MaxLength="3" runat="server" Width="30px" />
<asp:Button runat="server" ID="Addtocart" Text="Add To Cart" CommandName="AddToCart" ItemStyle-CssClass="btnCol" />
如果有人可以帮助我,那将非常感谢。
【问题讨论】:
-
我会创建一个文件处理程序 *.ashx 并让该组件返回图像。然后,您可以使用传入的适当参数将 ImageUrl 属性设置为该处理程序。
-
每次看到数据库中的最后一项。您打算如何在当前设计的页面中看到 7 行?
-
您正确获取了值问题是数据库中的每一行都将其绑定到同一组控件,因此最后只有最后一行显示给您,因为有数据库中没有更多行