CODEDIGEST
Home Articles CodeDigest Tutorials FAQs
Skip Navigation LinksHome » Article » ASP.Net Article » GridView with Image  Submit Articles and Win Geeky Prizes!!   You are not logged in.
Search
 

Product Spotlight
 

Technologies
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
Read more..

Read more..

 
Using Gridview to display Images from Database

By Satheesh babu
Posted On Feb 18, 2008
Article Rating: (Login)
Be first to rate
this article.
No of Comments: 8
Category:
Print this article.

Using Gridview to display Images from Database

In ASP.Net 1.x days, Datagrid is one of the most widely used control 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 Gridview, we can prevent some of the standard codes we will repeat for edit, update, delete, sort operations.

As we all know, displaying an image stored in a database in Gridview is bit complicated and not a straight forward task. I will use the power of HttpHandler to do this task easily. Before moving to the HttpHandler implementation, this article will discuss the implemention of image storage in the database.

 

Uploading image into BLOB Field:

 

Create a table 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. Next section will help us implementing the HttpHandler to retrieve the stored image from database.

 

Sponsors

Useful Books For Developers
Learning jQuery : Better Interaction Design and Web Development with Simple JavaScript Techniques More books..

Similar Articles

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>

The output will be like,

Source Code:

Download Source
Article Feedback
Title  
Submitted By  
Comment  
Enter the verification number
 
Comments
RbmBinaryImage
The RbmBinaryImage control will help you display images directly from your database. You could bind the Image field directly to the ImageContent property, also you could specify whether you want the display to be as a thumbnail or not and provide the thumbnail size.

to get it go to http://www.ramymostafa.com/?p=187
mr
when i try to view i got this error Conversion from string "ImageHandler.ashx?ImID=" to type 'Double' is not valid.
Re: reference dt
Thanks satheesh, figured it out, works great! :)
RE:reference dt
Thanks for pointing out Raymond. Its actually a DataTable Object.
DataTable dt = new DataTable();
reference dt
> ada.Fill(dt);
Where do you get this 'dt' from ?
(assuming it is data type...)
Dusty
here is another good example :http://laymensterm.blogspot.com/2008/12/simple-aspnet-vbnet-database-connection.html
Mr.
This works fine. Thanks
Mr
Great article! how couls i add pagination feature on the datagrid. when i try i get an error The GridView 'gvImages' fired event PageIndexChanging which wasn't handled.