<img alt="" src='ImageHandler.ashx?Item_ID=<%# Eval("Item_ID") %>' height="128" width="128" style="float: none; text-align: center" />
<asp:Label ID="Label1" runat="server" ForeColor="Blue" Text=""><%#DataBinder.Eval(Container.DataItem,"Item_Name")%></asp:Label>
後端程式碼
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=mydata;User Id=sa;Password=1234");
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("Select Item_ID,Item_Name From Item_Detail", conn);
DataTable dt = new DataTable();
da.Fill(dt);
DataList1.DataSource = dt.DefaultView;
DataList1.DataBind();
書本範例參考而來
<%@ WebHandler Language="C#" Class="ImageHandler" %>
using System;
using System.Web;
using System.IO;
using System.Configuration;
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//取得員工代號
string Item_ID=context.Request.QueryString["Item_ID"];
//透過ReadImage類別的GetImage()方法取得SQL Server中圖片資料
//其圖片儲存在MemoryStream之中回傳
MemoryStream ms = new ReadImage().GetImage(Item_ID);
if (ms != null)
{
//取得影像MemoryStream大小
int bufferSize = (int)ms.Length;
//建立 buffer
byte[] buffer = new byte[bufferSize];
//呼叫MemoryStream.Read,自MemoryStream 讀取至buffer,並傳回count
int countSize = ms.Read(buffer, 0, bufferSize);
//傳回影像buffer
context.Response.OutputStream.Write(buffer, 0, countSize);
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
using System;
using System.Data;
using System.IO;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
/// <summary>
/// ReadImage 的摘要描述
/// </summary>
public class ReadImage
{
public MemoryStream GetImage(string Item_ID)
{
SqlDataSource sqldsPhoto = new SqlDataSource("Data Source=.;Initial Catalog=mydata;User Id=sa;Password=1234", "Select Photo From Item_Detail where Item_ID=@paramID");
sqldsPhoto.SelectParameters.Add("paramID", TypeCode.Int32, Item_ID);
try
{
//透過SqlDataSource進行查詢
DataView dv = (DataView)sqldsPhoto.Select(DataSourceSelectArguments.Empty);
//回傳DataView第一個Row的Photo欄位資料
Byte[] PhotoImage = (Byte[])dv[0]["Photo"];
//回傳MemoryStream
return new MemoryStream(PhotoImage,0, PhotoImage.Length);
}
catch
{
return null;
}
}