Tuesday, June 10, 2008

Using Gridview to display Images from Database

In ASP.Net 1.x days Datagrid is one of the most common control that is used to display a table of data. With the introduction of ASP.Net 2.0 we have Gridview in the place of Datagrid, while the Datagrid control is still supported. With the introduction of Gridview we can prevent some of the standard code we will repeat for edit, update, delete, sort etc. Read my article about Gridview and Datasource controls here. In this article I will discuss how to display an image stored in a database field i.e. a BLOB field. As we know displaying an image from a database field in Gridview is not a straight forward task. I will use the power of HttpHandler to do this task easily. In the coming section of the article I will discuss how to upload the image into the database while in the further sections I will elaborate displaying the image in Gridview using HttpHandler.

Uploading image into BLOB Field:

Create a table in database with the following fields as shown in below figure.




Walkthrough:

1) Drag a FileUpload control into a WebForm (ImageUpload.aspx in our Example), a textbox for entering image name and a button for uploading.
2) Configure connection string in Web.Config file
3) Copy the following code into Upload button click event.

 Stream imgStream = fuImage.PostedFile.InputStream;
int imgLen = fuImage.PostedFile.ContentLength;
string imgName = txtImageName.Text;
byte[] imgBinaryData = new byte[imgLen];
int n = imgStream.Read(imgBinaryData,0,imgLen);

//use the web.config to store the connection string
SqlConnection connection = new SqlConnection(
ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
SqlCommand command = new SqlCommand("INSERT INTO Image (imagename,image)
VALUES ( @img_name, @img_data)", connection);

SqlParameter param0 = new SqlParameter("@img_name", SqlDbType.VarChar, 50);
param0.Value = imgName;
command.Parameters.Add(param0);

SqlParameter param1 = new SqlParameter("@img_data", SqlDbType.Image);
param1.Value = imgBinaryData;
command.Parameters.Add(param1);

connection.Open();
int numRowsAffected = command.ExecuteNonQuery();
connection.Close();
Where fuImage in the above code is the ID of the FileUpload control.

Implementing HttpHandler for fetching image from Database:

Create HttpHandler with name ImageHandler.ashx for fetching the image from database. Read my article about implementing an HttpHandler that fetches the image from the database by taking imageID as query string here. To display an image by calling the HttpHandler will be,

ImageHandler.ashx?ImID=100

ImageHandler.ashx implementation will be,

<%@ 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 will move to the implementation of Gridview to display the image using the above HttpHandler.

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>

Note: Remove "-" from above code
The output will be like,



Download Source

No comments:

.

.