前台代码:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID"
InsertVisible="False" ReadOnly="True" SortExpression="EmployeeID" />
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
<asp:TemplateField HeaderText="Photo" SortExpression="Photo">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Photo") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate><!--这里调用一般处理程序!!!注意这里必须使用' '号否则会出错!-->
<img src='Handler.ashx?EmployeeId=<%#Eval("EmployeeId") %>' /> </ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<br />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [EmployeeID], [LastName] FROM [Employees]">
</asp:SqlDataSource>
注意:如果数据绑定表达式作为属性的值,只要数据绑定表达式中没有出现双引号,那么<%#数据绑定表达式%>的最外层用双引号或者单引号都可以。如果数据绑定表达式中出现双引号,则<%#数据绑定表达式%>的最外层最好要用单引号。
HttpHanlder程序:
<%@ WebHandler Language="C#" Class="ImageHandler" %> using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Configuration; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; public class ImageHandler : IHttpHandler { //取得数据连接配置 static ConnectionStringSettings connString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"]; public void ProcessRequest(HttpContext context) { MemoryStream ms=null; try { //取得员工代号 string EmployeeID = context.Request.QueryString["EmployeeID"]; //通过ReadImage类的GetImage()方法取得SQL Server中图片资料 //建立Sql命令 string strSQL = "Select Photo from Employees where EmployeeID=@paramEmployeeID"; //建立SqlDataSource SqlDataSource sqldsPhoto = new SqlDataSource(connString.ConnectionString, strSQL); sqldsPhoto.SelectParameters.Add("paramEmployeeID", TypeCode.Int32, EmployeeID); //通过SqlDataSource进行查詢 DataView dv = (DataView)sqldsPhoto.Select(DataSourceSelectArguments.Empty); //回传DataView第一个Row的Photo字段资料 if (!(dv[0]["Photo"] is DBNull)) {//注意:这里需要判断下是否是DBNull否则会报异常,虽然这个例子没有抛出异常. Byte[] PhotoImage = (Byte[])dv[0]["Photo"]; ms = new MemoryStream(PhotoImage, 0, PhotoImage.Length); } } catch { } 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; } } }