How to Insert Images into Database and Display it in GridView

How to Insert Images into Database and Display it in GridView

Here we are going to display the image in the gridview by fetching the data from the table.The following article explicate the method of inserting images and pictures into SQL Server database table and display it in an Asp.Net GridView control with the help of Handler.aspx.

First we have to create a SQL server DB table, let me explain the SQL Server database table structure we are going to use to insert the image. The table must contain a column of data type IMAGE. This image data type is a Variable-length binary data with a maximum length of 2^31 - 1 (2,147,483,647) bytes. For storing the image into DB image column we have to convert it into binary string with the help of some IO classes and then insert into the table.
For demonstration, we are going to create a table named ImageGallery with four columns in the following structure
Column Name Description Data Type
Img_Id Identity column for Image Id int
Img_Content Store the Image in Binary Format image
Img_Type Store the Image format (i.e. jpeg, gif, png, etc.) varchar
Img_Size Store the Image File Size bigint

After we create table in the database,start the coding part.
> Open your web application in Visual Studio 2005 or 2008, drag and drop File Upload control and a Button control into the web page.
> In the code-behind, add the namespace System.IO.

using System.IO;

>. In the Button’s Button1_Click event, write the following code

if (FileUpload1.PostedFile != null
&& FileUpload1.PostedFile.FileName != "")

byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile Image = FileUpload1.PostedFile;
Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);

SqlConnection myConnection = new SqlConnection(“Your Connection String”);
SqlCommand storeimage = new SqlCommand("INSERT INTO ImageGallery "
+"(Img_Content, Img_Type, Image_Size) "
+" values (@image, @imagetype, @imagesize)", myConnection);
storeimage.Parameters.Add("@image", SqlDbType.Image, myimage.Length).Value = myimage;
storeimage.Parameters.Add("@imagetype", SqlDbType.VarChar, 100).Value
= FileUpload1.PostedFile.ContentType;
storeimage.Parameters.Add("@imagesize", SqlDbType.BigInt, 99999).Value
= FileUpload1.PostedFile.ContentLength;


To upload the image from any location (your local drive) to the server, we have to use HttpPostedFile object(since it a server). Point the uploaded file to HttpPostedFile object. Then the InputStream.Read method will read the content of the image by a sequence of bytes from the current stream and advances the position within the stream by the number of bytes it read. So myimage contains the image as binary data. Now we have to pass this data into the SqlCommand object, which will insert it into the database table.

Display the Image in a GridView with Handler.ashx

So far, the article explains the way to insert images into the database. The Image is in the database in binary data format. Retrieving this data in an ASP.NET web page is fairly easy, but displaying it is not as simple. The basic problem is that in order to show an image in an apsx page, you need to add an image tag that links to a separate image file through the src attribute or you need to put an Image control in your page and specify the ImageUrl.

For example:

<asp:Image ID="Image1" runat="server" ImageUrl="YourImageFilePath" />

Unfortunately, this approach will not work if you need to show image data dynamically. Although you can set the ImageUrl attribute in code, you have no way to set the image content programmatically. You could first save the data to an image file on the web server’s hard drive, but that approach would be dramatically slower, wastes space, and raises the possibility of concurrency errors if multiple requests are being served at the same time and they are all trying to write the same file.

In these situations, the solution is to use a separate ASP.NET resource that returns the binary data directly from the database. Here HTTP Handler class comes to center stage.
What is Handler?

An ASP.NET HTTP Handler is a simple class that allows you to process a request and return a response to the browser. Simply we can say that a Handler is responsible for fulfilling requests from the browser. It can handle only one request at a time, which in turn gives high performance. A handler class implements the IHttpHandler interface.

For demonstration, we are going to display the image in the GridView control along with the data we stored in the table. Here are the steps required to accomplish this:

>. Create a Handler.ashx file to perform image retrieval. This Handler.ashx page will contain only one method called ProcessRequest. This method will return binary data to the incoming request. In this method, we do normal data retrieval process and return only the Img_Content field as bytes of array.

The sample code follows

public void ProcessRequest (HttpContext context)
SqlConnection myConnection = new SqlConnection(“YourConnectionString”);
string sql = "Select Img_Content, Img_Type from ImageGallery where Img_Id=@ImageId";
SqlCommand cmd = new SqlCommand(sql, myConnection);
cmd.Parameters.Add("@ImageId", SqlDbType.Int).Value = context.Request.QueryString["id"];
SqlDataReader dr = cmd.ExecuteReader();
context.Response.ContentType = dr["Img_Type"].ToString();


>. Place a GridView control in your aspx page, with one TemplateField column, add an Image control into the TemplateField's ItemTemplate section. Specify the ImageUrl property as

<asp:Image ID="Image1" runat="server" ImageUrl='<%# "Handler.ashx?id=" + Eval("Img_Id") %>' />
Now we can bind the GridView control to display all the records in the table as follows

GridView1.DataSource = FetchAllImagesInfo();

Before you bind the GridView, you should write the FetchAllImagesInfo method to return all the records with their image data from the table and then you have to load the images into the GridView control. The code for FetchAllImagesInfo is

public DataTable FetchAllImagesInfo())
string sql = "Select * from ImageGallery";
SqlDataAdapter da = new SqlDataAdapter(sql, "Your Connection String");
DataTable dt = new DataTable();
return dt;

That's it. When you run your project, you can see the loaded in images got to the GridView control.
This is a very simple explanation to store images into the data source and to retrieve it back to display in the webpage. You can make the logic even simpler and even elaborate it upto your requirements.


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: