- 如何在控件GridView中显示数据库里的图片
-
Asp.Net GridView中显示数据库里的图片2007年01月29日 星期一 18:09很多人开始有这个疑问,GridView控件中的ImageField没有DataField属性,那么如何才能绑定到SQL Server中的Image Field自从DynamicImage控件从beta2中消失后,这就成了个问题。但是,ASP.NET2.0随之也给我们带来了另外一种解决方案,那就是方便地利用HttpHandler(.ashx)动态显示数据库中的图片,这点在VS2005中提供了PersonalWebSite等模版中已经给出方案:通过ashx动态获取数据库中的某条图片数据,然后在GridView等控件的自定义模版中安置一个Image控件,并设置Image控件的ImageUrl属性为类似 XXX.ashxphotoId=1 即可显示图片。
下面为Handler.ashx的代码:
using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web;
using System.Configuration;
public class Handler : IHttpHandler ...{
public bool IsReusable ...{
get ...{
return true;
}
}
public void ProcessRequest(HttpContext context) ...{
// Set up the response settings
context.Response.ContentType = "image/jpeg";
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.BufferOutput = false;
int photoId = -1;
Stream stream = null;
if (context.Request.QueryString["PhotoID"] != null &&
context.Request.QueryString["PhotoID"] != "") ...{
photoId = Convert.ToInt32(context.Request.QueryString["PhotoID"]);
stream = GetPhoto(photoId);
}
const int buffersize = 1024 * 16;
- 与本文主题相关的文章
