我正在尝试使用 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" />
如果有人可以帮助我,那将非常感谢。