CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Using Gridview to display Images from Database

By Satheesh babu
Posted On Feb 18, 2008
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 44
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.

 




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
Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Wonderful!!!!!!!!!!!
This is simply awesome!!!!!!!!!!!
swf file
can not show swf files when show pictures in Defulat page only show jpg
Gracias
eeeeeyyyy.....Muchas Gracias, me sirvio demasiado, ya no sabia q inventarme.

Slds
Error "stream" asked by selvi
use

using System.IO;

for your Stream error..
problem
<%@ WebHandler Language="C#" Class="ImageHandler" %>
This line don't show in my Handler.ashx page when i create it.
It's my big problem.
What can i do??
Thank you
very good
thank for this article
anand
good article
sds
dfdf
Mr.
I am getting some error due to having the imagID as varchar(50) and not int, what need to be changed in the code to make it work with imageID as varchar?

Thanks
Thank you!
Just simply wonderful. Thank you thank you thank you. You are a life saver.
display image
how to display image
gh
but img not display
mr
SqlDataReader dr = command.ExecuteReader();Line 1: Incorrect syntax near '='.
Thanks
Nice & Easy

Thanks a Lot.
Display img
thanks `^-^`
retrive image in gridview
i use this code in my project but it can not display the image.
my image store in database in binary formate.
tell me what i should do...???
Awesome
Awesome Work Satheesh babu. You Made My Day Today?

Thank u so much for this artical.


Hammad Khan
files disply in gridview
hi pls someone help me
how to display the files(.jpg,.txt,.doc,.pdf) in gridview from database.
Error
When i m executing this code then there is a ERROR-

"Compiler Error Message: CS0103: The name 'fuImage' does not exist in the current context"

Please give me Solution.
IN Vb.net codding
Hi i am converting all above code in vb.net but i am getting error Converting String to Double , I try to put & inplace of + in grideview code so there is no error but image is not display
Helping Article
it helps me thanx
MR
Hi Pls help in solving the beloe mentioned problem

how to display image in img control from database, when connected to server.

pls someone help me out .

thanks and regards
GURU.
Error
if i insert new image through aspx it loaded in database fine. when i bind the grid agin the image is not comming.first time page loading all images display proper including new image.
Great
Nice Info....i like it...Free Directory Submit at: http://www.submitfreelistings.com/
Nice
This is absolutely nice and informative..i will use this code...www.netcomwebtech.com
RE: error
Declare dt like below,

DataTable dt = new DataTable();

error
the name dt does not exist in the current context
Great Article
I was trying to do it as simple as this code, thanks for your post.
Implementing HttpHandler for fetching image from Database:
this article was of great help.I was trying to do this task frm past 7 days bt i was unable to do.This artice help me alot in completing my task.thamks for this valuable article
Help Me
I need to pass 2 parameters to image handler (image id and category id) COULD YOU HELP PLEASE.....
Modify for VB Coders
Hey All, If you are a VB Coder and get an error for Converting String to Double - Its the + sign in the HTML for the GridView. Change it to an & and your good to go. Great Tutorial. Thanks.
seo services
Thanks for the sharing of such information. we will pass it on to our readers. This is a great reading. Thanking you. <a href="http://www.seochampion.com">Professional seo services</a>
Guaranteed SEO Services, Professional SEO Services, Organic SEO Services
this is very useful code, www.ewittas.com
Error "stream"
I am getting error in the following code for Upload btn

Stream imgStream = FileUpload1.PostedFile.InputStream;

Error: The type or namespace name 'Stream' coul not be found ( are you missing a using irective or an assembly reference?)

Pls help me...
sadas
asdasdasd
.net Training Classes
This code is so help ful to me...Thanks

.net Training Classes

Sharma Web Academy
www.sharmawebacademy.com
Dotnet Training Classes
Contact Us
harish.solanki@sharmainfoway.com
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.