Click here to Skip to main content
Click here to Skip to main content

GridViewImages from DB in ASP.NET using C#

, 26 Jun 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
GridViewImages from DB in ASP.NET using C#

Introduction

This article is about inserting images into database and displaying them in GridView through Handler.ashx.

This article explains the method of inserting images and pictures into SQL Server database table and displays it in an ASP.NET GridView control with the help of Handler.aspx.

To make your task easier, this article explains the methods of storing the images into data source. There are many advantages of saving the images into database. The main advantage is easy management of images. You can control the number and size of images stored in your server. You can remove all unnecessary images from the database in a single SQL query and you can backup the image data easily. On the other hand, you should be generous in keeping sufficient memory store in your database server.

Inserting Image into Database

To start with, let me explain the SQL Server database table structure we are going to use to insert the image. The table you are going to create to store the image 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. To store the image into this column, we are going to convert it into a 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
Image_Content Store the Image in Binary Format image
Image_Type Store the Image format (i.e. JPEG, GIF, PNG, etc.) varchar
Image_Size Store the Image File Size bigint

After we create a table in the database, we can start the coding part.

  1. Open your web application in Visual Studio 2005, drag and drop File Upload control and a Button control into the web page.
  2. In the code-behind, add the namespace System.IO.
    using System.IO;
  3. 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 "
    +"(Image_Content, Image_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; 
    
    myConnection.Open(); 
    storeimage.ExecuteNonQuery(); 
    myConnection.Close(); 
    }

To upload the image from any location (your local drive) to the server, you have to use HttpPostedFile object. 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 advance 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" />
<SCRIPT src="file:///C:/Documents%20and%20Settings/nagasridhar/Desktop/
Inserting%20Images%20into%20Database%20and%20Display%20it%20in%20GridView%20
through%20Handler_ashx%20-%20Storing%20Images%20in%20SQL%20Server%20DB,
%20Store%20and%20Display%20Image%20Dynamically%20from%20Database_files/show_ads.js"
  type=text/javascript> </SCRIPT>

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, waste space, and raise 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 this article 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:

  1. 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 Image_Content field as bytes of array.

    The sample code follows:

    public void ProcessRequest (HttpContext context) 
    { 
        SqlConnection myConnection = new SqlConnection(); 
        myConnection.Open(); 
        string sql = "Select Image_Content from ImageGallery where Img_Id=@ImageId"; 
        SqlCommand cmd = new SqlCommand(sql, myConnection); 
        cmd.Parameters.Add("@ImageId", SqlDbType.Int).Value =
           context.Request.QueryString["id"]; 
        cmd.Prepare(); 
        SqlDataReader dr = cmd.ExecuteReader(); 
        dr.Read(); 
        context.Response.ContentType = dr["Image_Type"].ToString(); 
        context.Response.BinaryWrite((byte[])dr["Image_Content"]); 
    }
  2. 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:TemplateField> 
     <ItemTemplate> 
        <asp:Image ID="Image1" runat="server" ImageUrl='<%# "Handler.ashx?id=" + Eval(
           "Img_Id") %>' /> 
     </ItemTemplate> 
    </asp:TemplateField>
    <SCRIPT src="file:///C:/Documents%20and%20Settings/nagasridhar/Desktop/
     Inserting%20Images%20into%20Database%20and%20Display%20it%20in%20GridView%20
     through%20Handler_ashx%20-%20Storing%20Images%20in%20SQL%20Server%20DB,
     %20Store%20and%20Display%20Image%20Dynamically%20from%20Database_files/
     show_ads.js"
        type=text/javascript> </SCRIPT>
  3. Now we can bind the GridView control to display all the records in the table as follows:
    GridView1.DataSource = FetchAllImagesInfo();
    GridView1.DataBind();

    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(); 
        da.Fill(dt); 
        return dt; 
    }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Naga Sridhar Madiraju
Web Developer Pasca Software Solutions
India India
No Biography provided

Comments and Discussions

 
QuestionImage resize Pinmembernikolakuzmanovski17-Jan-14 17:47 
QuestionURGENT PinmemberMember 877633524-Jul-12 1:29 
GeneralMy vote of 5 PinmemberMarcio_Coelho17-Dec-10 6:22 
Generalerror Pinmembernum bhaskar16-Oct-08 2:57 
GeneralHTTP Error 404 - Not Found Pinmemberalyy04068-Oct-08 18:08 
GeneralTry this Pinmembermayurmv5-Sep-08 18:21 
Generalgridview PinmemberRajaraman20-Jun-08 0:47 
GeneralRe: gridview PinmemberNaga Sridhar Madiraju20-Jun-08 0:57 
GeneralRe: gridview Pingroupfaizyab 200927-Sep-09 23:39 
Generalgridview PinmemberRajaraman20-Jun-08 0:31 
This coding not work.. where is insert table field img_id
GeneralRe: gridview PinmemberNaga Sridhar Madiraju20-Jun-08 0:39 
Questionhi PinmemberTanmay Broachwala28-Apr-08 20:41 
GeneralRe: hi PinmemberNaga Sridhar Madiraju28-Apr-08 20:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 26 Jun 2009
Article Copyright 2008 by Naga Sridhar Madiraju
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid