Geeks With Blogs

News

Microsoft MVP


Moderator at CodeASP.NET


Quiz Master




free counters
Free counters
Added on January 19,2012


Follow Me @vmsdurano

A bit About Me



Disclaimer
The opinions expressed herein are my own personal opinions and does not represent the opinions of my employers. Nor does it represent the opinion of my dog, because I don’t have one.


Vinz' Blog (ProudMonkey) "Code, Beer and Music ~ my way of being a programmer"

I wrote this demo because I observed that lots of people in the forum (forums.asp.net) always ask questions on how to display Image that was stored in the database to GridView control.

Before reading this example, be sure that you have already know how to upload image to the database. If you are not familiar with it then I would suggest you to read my previous example about “Uploading and Storing Images to Database in ASP.NET”.

In this demo, we are going to use a Handler.ashx file for fetching the binary data from the database and stream it.

What is a Handler?

A handler is responsible for fulfilling requests from a browser. Requests that a browser manages are either handled by file extension (or lack thereof) or by calling the handler directly. Only one handler can be called per request. A handler does not have any HTML static text like .aspx or .ascx files. A handler is a class that implements the IHttpHandler interface. If you need to interact with any Session information, you will also need to implement IRequiresSessionState. If you want to make an asynchronus handler, you will need to implement the IHttpAsyncHandler interface instead of the IHttpHandler interface.

STEP 1: Creating a Handler file (.ashx)

If you are not familiar creating a handler file in Visual Studio then follow these few steps below :

* Right Click on the Project and select “Add New Item”

* On the popup window, select the “Generic Handler” file. See the screen shot below


* Click Add

STEP 2: Setting up the GridView

For the simplicity of this demo, I set up the GridView like below in the WebForm:

ASPX:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:BoundField  DataField="Id" ReadOnly="true" HeaderText="Image ID"/>
            <asp:BoundField  DataField="ImageName" HeaderText="File Name"/>
            <asp:BoundField  DataField="ImageType" HeaderText="Image File Type"/>
            <asp:BoundField  DataField="ImageSize" HeaderText="Image Size (bytes)"/>
            <asp:TemplateField HeaderText="Image View" ControlStyle-Width="100px" ControlStyle-Height="100px">
                <ItemTemplate>
                    <asp:Image ID="Image" runat="server" ImageUrl='<%# "Handler.ashx?id=" + Eval("Id")  %>' />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
</asp:GridView>

Noticed that we are using an Image control within the TemplateField column of the GridView for displaying the images. You will also observe that the ImageUrl property of the Image Control are being set declaratively with the path of the Handler file that we have just created in STEP 1 and pass the Id as the querystring value.

STEP 3: Streaming the Image Binary file from the database

Here’s the code block for streaming the image file in the handler file.

<%@ WebHandler Language="C#" Class="Handler" %>

 
using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Collections.Specialized;
 
public class Handler : IHttpHandler {

    public string GetConnectionString()
    {
        //sets the connection string from your web config file "ConnString" is the name of your Connection String
        return System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
    }

    public void ProcessRequest(HttpContext context)
    {
        string id = context.Request.QueryString["id"]; //get the querystring value that was pass on the ImageURL (see GridView MarkUp in Page1.aspx)

        if (id != null)
        {

            MemoryStream memoryStream = new MemoryStream();
            SqlConnection connection = new SqlConnection(GetConnectionString());
            string sql = "SELECT * FROM TblImages WHERE Id = @id";
            
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.AddWithValue("@id", id);
            connection.Open();

            SqlDataReader reader = cmd.ExecuteReader();
            reader.Read();

            //Get Image Data
            byte[] file = (byte[])reader["Image"];

            reader.Close();
            connection.Close();
            memoryStream.Write(file, 0, file.Length);
            context.Response.Buffer = true;
            context.Response.BinaryWrite(file);
            memoryStream.Dispose();
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
}

The code above fetches the image data from the database based from the Id that was passed through the querystring and then streams the image data using the MemoryStream object.

STEP 4: Binding GridView

Here are the code blocks for binding the Grid with image data from the database.

   public string GetConnectionString(){
        //sets the connection string from your web config file "ConnString" is the name of your Connection String
        return System.Configuration.ConfigurationManager.ConnectionStrings["MyConsString"].ConnectionString;
    }

 
    private void BindGrid()
    {

        DataTable dt = new DataTable();
        SqlConnection connection = new SqlConnection(GetConnectionString());
        try
        {
            connection.Open();
            string sqlStatement = "SELECT * FROM TblImages";
            SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
            SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);

            sqlDa.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Fetch Error:";
            msg += ex.Message;
            throw new Exception(msg);
        }
        finally
        {
            connection.Close();
        }
    }

    protected void Page_Load(object sender, EventArgs e){
        if (!Page.IsPostBack){
            BindGrid();
        }
    }

As you can see, the code above is very straight forward and self explanatory. :) 

You can see the screen shot of the page output below:


 

That's it guys! Hope you will find this example useful!

Posted on Friday, April 24, 2009 8:52 AM ADO.NET , ASP.NET , C# , GridView | Back to top


Comments on this post: FAQ: Displaying Image from Database to GridView Control

# re: FAQ: Displaying Image from Database to GridView Control
Requesting Gravatar...
ThanX 4 God Code
Left by Puneet Malviya on May 24, 2009 6:08 PM

# re: FAQ: Displaying Image from Database to GridView Control
Requesting Gravatar...
Thanks for the code and explanation.
Its very useful.
Left by Avinash Patil on Jun 11, 2009 1:17 AM

# re: FAQ: Displaying Image from Database to GridView Control
Requesting Gravatar...
Thank you! You're codes were very easy to read and it worked!
Left by anonymous on Sep 04, 2009 5:27 AM

# re: FAQ: Displaying Image from Database to GridView Control
Requesting Gravatar...
Thanks for your code and explanation.

Its very easy and helpful.
again


thanks
Left by Ramesh Mishra on Feb 19, 2010 8:09 PM

# re: FAQ: Displaying Image from Database to GridView Control
Requesting Gravatar...
Any chance this solution could be provided in VB? I'm still searching for a solution to retrieve images from MS SQl and display in website.
Left by Matt on May 12, 2010 9:36 AM

# re: FAQ: Displaying Image from Database to GridView Control
Requesting Gravatar...
love u man godly code
Left by ELSON on Mar 20, 2011 3:48 PM

# re: FAQ: Displaying Image from Database to GridView Control
Requesting Gravatar...
thank you
your code is good
if you add (try catch) it will be beautiful ;)
Left by ayaz on Jul 25, 2011 2:24 AM

# re: FAQ: Displaying Image from Database to GridView Control
Requesting Gravatar...
hi got error in this how to solve .Specified argument was out of the range of valid values.
Parameter name: offset
Left by siva on Aug 08, 2011 4:00 PM

# re: FAQ: Displaying Image from Database to GridView Control
Requesting Gravatar...
complete understanding........good work.really acknowledgeable
Left by Shivani on Jan 22, 2013 4:44 PM

comments powered by Disqus

Copyright © Vincent Maverick Durano | Powered by: GeeksWithBlogs.net | Join free