我是Asp.Net& C#。我正在开发一个博客。我能够将文件保存在SQL Server的文件夹和图像路径中。现在我想从路径存储在SQL Server表中的文件夹中检索图像。
我试试这个:
ASPX标记:
<body>
<form id="form1" runat="server">
<div class="row">
<div class="page-header"></div>
<div class="col-lg-3">
<asp:Image ID="Image1" CssClass="img-thumbnail" runat="server" />
</div>
</div>
</form>
</body>
代码隐藏:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;
namespace Admin_Panel
{
public partial class Admin : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["stuconnection"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
string qry = "SELECT * FROM upload";
SqlCommand cmd = new SqlCommand(qry, con);
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
var filep = dr.GetString(1);
Image1.ImageUrl ="~/Images/" + filep;
}
con.Close();
}
}
}
但上面的代码只显示一张图片。
我想要的是什么:我想使用foreach
循环或类似循环的方式显示所有图像,但我不知道该怎么做。
任何帮助将不胜感激。
答案 0 :(得分:3)
首先,你应该使用asp.repeater:
<asp:Repeater ID="RptImages" runat="server">
<ItemTemplate>
<asp:Image ID="Img" runat="server" ImageUrl='<%# Container.DataItem %>'/>
</ItemTemplate>
</asp:Repeater>
否则:
public partial class Admin : System.Web.UI.Page
{
List<String> images = new List();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["stuconnection"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
string qry = "SELECT * FROM upload";
SqlCommand cmd = new SqlCommand(qry, con);
SqlDataReader dr;
con.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
var filep = dr.GetString(1);
images.add(String.Concat("~/Images/", filep);
}
con.Close();
RptImages.DataSource = images;
RptImages.DataBind();
}
}