Asp.net 从数据库在GridView中显示图像?
我将图像作为二进制数据保存在SQL server数据库中。现在我想在Gridview中显示这些图像。但是没有直接从数据库读取数据的web控件。Web图像控件需要Asp.net 从数据库在GridView中显示图像?,asp.net,gridview,Asp.net,Gridview,我将图像作为二进制数据保存在SQL server数据库中。现在我想在Gridview中显示这些图像。但是没有直接从数据库读取数据的web控件。Web图像控件需要ImageUrl属性,因此无法使用此属性,因为我的图像位于数据库中。不过,我可以将图像存储在文件夹中,但我需要一些不同的方法,直接从数据库读取图像数据并显示在网格中。博客可能会给您一些帮助 使用通用处理程序,您可以将二进制数据转换为图像并显示它 代码: 将图像控件url设置为 Image1.ImageUrl=“~/ShowImage.as
ImageUrl
属性,因此无法使用此属性,因为我的图像位于数据库中。不过,我可以将图像存储在文件夹中,但我需要一些不同的方法,直接从数据库读取图像数据并显示在网格中。博客可能会给您一些帮助
使用通用处理程序,您可以将二进制数据转换为图像并显示它 代码: 将图像控件url设置为
Image1.ImageUrl=“~/ShowImage.ashx?id=“+id代码>
其中ShowImage.ashx是一个通用处理程序文件
using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
public class ShowImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
Int32 empno;
if (context.Request.QueryString["id"] != null)
empno = Convert.ToInt32(context.Request.QueryString["id"]);
else
throw new ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
Stream strm = ShowEmpImage(empno);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
//context.Response.BinaryWrite(buffer);
}
public Stream ShowEmpImage(int empno)
{
string conn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
SqlConnection connection = new SqlConnection(conn);
string sql = "SELECT* FROM table WHERE empid = @ID";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ID", empno);
connection.Open();
object img = cmd.ExecuteScalar();
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
finally
{
connection.Close();
}
}
}
您在SO中搜索过现有答案吗?是的,我搜索过,但找不到合适的答案。它会直接从处理程序中获取图像吗?@eraj:是的,这在我的情况下有效。好吧,请再试一次,如果你发现任何问题,请告诉我?