如何动态地从数据库中获取图像?

时间:2016-03-16 11:07:38

标签: c# asp.net

我正在尝试从我的数据库中获取图像,我可以逐个手动获取图像。下面的代码是asp.net及其C#:

  <asp:Image ID="img1" runat="server" />
            <asp:Image ID="img2" runat="server" />
            <asp:Image ID="img3" runat="server" />
            <asp:Image ID="Image3" runat="server" />
            <asp:Image ID="img4" runat="server" />
            <asp:Image ID="img5" runat="server" />
            <asp:Image ID="img6" runat="server" />
            <asp:Image ID="Image7" runat="server" />
            <asp:Image ID="Image8" runat="server" />
            <asp:Image ID="Image9" runat="server" />


    dr.Read();
    img1.ImageUrl = "~/Resimler/800/" + dr[2].ToString();
    dr.Read();
    img2.ImageUrl = "~/Resimler/800/" + dr[2].ToString();
    dr.Read();
    img3.ImageUrl = "~/Resimler/800/" + dr[2].ToString();
    dr.Read();
    img4.ImageUrl = "~/Resimler/800/" + dr[2].ToString();
    dr.Read();
    img5.ImageUrl = "~/Resimler/800/" + dr[2].ToString();
    dr.Read();
    img6.ImageUrl = "~/Resimler/800/" + dr[2].ToString();

所以我想动态获取图片。

1 个答案:

答案 0 :(得分:1)

dr绑定到images表后,您可以循环显示图像并将这些图像设置为图像组件。

//We are creating a List to contain our Image components
List<Image> ArrayImages = new List<Image>();
//Insert Image components into array
ArrayImages.Add(img1);
ArrayImages.Add(img2);
ArrayImages.Add(img3);
//TODO: Add other Image components in array

int counter = 0; //We will use this counter to identify array index
while(dr.Read()){
  //Assign image url to Image component in our array's current index
  ArrayImages[counter].ImageUrl = "~/Resimler/800/" + dr[2].ToString();
  //Implementing counter for next index in our Image array
  counter++;
}