2012-11-25 83 views
0

我想用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" /> 

如果有人能帮我,将是巨大的感谢。

+1

我想创建一个文件处理程序* .ashx的并让图像由该组件返回。然后,您可以将ImageUrl属性设置为该处理程序并传入适当的参数。 – Candide

+0

每次看到数据库中的最后一项时。你打算如何看待当前设计中的7行页面? –

+0

您正确地获取值问题是您将数据库的每一行绑定到同一组控件,因此最终只有最后一行显示给您,不会因为数据库中没有更多行而更改 – sajanyamaha

回答

1

则应该在数据库中的图像列类型为byte []并使用此方法拖来获取和设置图像:

public BitmapImage ImageFromBuffer(Byte[] bytes) 
{ 
    MemoryStream stream = new MemoryStream(bytes); 
    BitmapImage image = new BitmapImage(); 
    image.BeginInit(); 
    image.StreamSource = stream; 
    image.EndInit(); 
    return image; 
} 

public Byte[] BufferFromImage(BitmapImage imageSource) 
{ 
    Stream stream = imageSource.StreamSource; 
    Byte[] buffer = null; 
    if (stream != null && stream.Length > 0) 
     { 
      using (BinaryReader br = new BinaryReader(stream)) 
       { 
        buffer = br.ReadBytes((Int32)stream.Length); 
       } 
     } 

    return buffer; 
} 
0

我认为你的问题标题应该更像“我如何在我的页面上显示数据库结果集”。

答案是你应该使用数据绑定。通过这种方式,您可以设置数据项在页面上的外观。然后,您可以将一组记录/对象引入此列表(使用它的布局),并且它们都按布局中的定义进行渲染。

这里是一个小例子:

在你的aspx代码:

<asp:DataList id="dlItems" runat="server"> 
     <ItemTemplate> 
      <%# Eval("ID") %> 
      <%# Eval("Name") %> 
      <%# Eval("price") %> 
     </ItemTemplate> 
</asp:DataList> 

在你的CS代码:

dlItems.DataSource = dtenergy; 
dlItems.DataBind(); 

对于你的问题的图像部分,请参阅其他像这样的线程:Display image from database in ASP.net with C#

有关数据绑定的详细信息,请参阅c在这里看看:http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.itemdatabound.aspx