Implementing HttpHandler for fetching image from Database:
- Create a HttpHandler with the name "ImageHandler.ashx". Read my previous article on implementing an HttpHandler which fetches the image stored in the database by accepting imageID as query string here.
- The HttpHandler can be called by,
ImageHandler.ashx?ImID=100
And ImageHandler.ashx implementation is,
<%@ WebHandler Language="C#" Class="ImageHandler" %>
using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
public class ImageHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string imageid = context.Request.QueryString["ImID"];
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
connection.Open();
SqlCommand command = new SqlCommand("select Image from Image where ImageID="+imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((Byte[])dr[0]);
connection.Close();
context.Response.End();
}
public bool IsReusable {
get {
return false;
}
}
}
We can use this HttpHandler to retrieve the image from database and can bind it to the Gridview. Next section will help you to do that.
Binding it to a Gridview:
1) Drag a Gridview into the WebForm and name it as gvImages,
2) Use the following code for binding the Gridview,
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
SqlCommand command = new SqlCommand("SELECT imagename,ImageID from [Image]", connection);
SqlDataAdapter ada = new SqlDataAdapter(command);
ada.Fill(dt);
gvImages.DataSource = dt;
gvImages.DataBind();
Gridview HTML will be,
<asp:GridView Width="500px" ID="gvImages" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:BoundField HeaderText = "Image Name" DataField="imagename" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "ImageHandler.ashx?ImID="+ Eval("ImageID") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
|