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"

This example is a continuation of my previous example about “Uploading and Storing Images to Database in ASP.NET”.

In this demo, I’m going to show how to display image (binary format) from database to ASP Image control and display its corresponding image information based on user selection.

In this demo, we are going to use a Handler.ashx file for fetching the binary data from the database and then 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: Setting up the UI.

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


As you can see the UI is very simple. It just contain a single DropDownList control wherein a user can select the filename of the image they want to show. I also has an Image Control for displaying the actual image with three Label control for displaying the image information in the page.

Now let’s start creating the Handler file.

STEP 2: Creating the 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 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 basically 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.

Since we are done creating the handler file with the relevant codes for fetching and streaming the binary data from the database then let’s go back to the WebForm where you have set the UI for displaying the image.

STEP 4: Binding the DropDownList with the List of the Image Filenames from the database.

Here’s the code block below:

private void BindFileNames()
{ 

        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)
            {
                DropDownList1.DataSource =dt;
                DropDownList1.DataTextField = "ImageName"; // the items to be displayed in the list items
                DropDownList1.DataValueField = "Id"; // the id of the items displayed
                DropDownList1.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)
        {
            BindFileNames();
        }
}

As you can see from the above code blocks, we set the “ImageName” in the DataTextField and set the “Id” in the DataValueField. Please note that the value of "Id" will be passed through the handler file and fetch the image data based on that Id.

STEP 5: Displaying the Image based on the value selected from the DropDownList

Here’s the code block below:

    private void GetImageInfo(string id)
    {

        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 Information
        Label1.Text = reader["ImageName"].ToString();
        Label2.Text = reader["ImageType"].ToString();
        Label3.Text = reader["ImageSize"].ToString() + " (bytes)";
 
        reader.Close();
        connection.Close();
    }

    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DropDownList1.SelectedIndex > 0)
        {
            //Set the ImageUrl to the path of the handler with the querystring value
            Image1.ImageUrl = "Handler.ashx?id=" + DropDownList1.SelectedItem.Value;
            //call the method to get the image information and display it in Label Control
            GetImageInfo(DropDownList1.SelectedItem.Value);
        }
    }

As you can see the code above is very straight forward. It simply set’s the ImageUrl of the Image control by calling the path of the Handler file with the querystring value. It also calls the GetImageInfo() method for displaying the additional information of the Image in the page such as the filename, file size and file type.

Take a look at the screen shot below for the page output.

 


 


That’s it! I hope you will find this example useful!

Posted on Friday, April 24, 2009 3:15 AM ADO.NET , ASP.NET , C# | Back to top


Comments on this post: Displaying Image to Image Control based on User Selection in ASP.NET

# Very good e.g.
Requesting Gravatar...
Best e.g. given

Thanks
Left by From Jaysingh on Apr 28, 2009 10:26 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
Thank you sir .

that was a very helpful e.g.
Left by Hajjaj jamal al hajjaji on Jun 15, 2009 3:06 AM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
Was definitely a great effort... HATS OFF...

and a Really BIG Thanks..
Left by Raj kiran on Jul 30, 2009 5:37 AM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
very good example u r given
keep it up.
thank you
Left by pavitra on Aug 21, 2009 7:30 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
Thank you very much. It's very important for me.
Left by fblood on Aug 26, 2009 12:18 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
noredirection on handler
n thus no display of image
Plz tell me the reason
Left by Monika on Aug 27, 2009 7:30 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
And someone now how to show image in detaisview (in a row) without ImageUrl??
Left by Tiago on Sep 29, 2009 10:45 AM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
Article is very good. But if a explanatory note for "why to use generic handler" is given then it makes article perfect.
Left by Shilpa on Mar 04, 2010 7:53 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
Thank you for the article, I was very helpful. Thanks again.
Left by Andres ☆☆☆☆☆ on Apr 25, 2010 12:07 AM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
Thank you good example
Left by Adam on Jul 13, 2010 1:34 AM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
Thank u so much sir.........
Left by sri on Dec 03, 2010 5:13 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
very nice article.....

thankyou !!!!!!
Left by phani c on Dec 15, 2010 1:40 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
thank you , that's great!
Left by wangli on Jan 28, 2011 11:19 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
Thank You very much !!!
Left by saroj panda@BBSR on Mar 07, 2011 6:23 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
Really you are brilliant. from lost a month i was trying this. Your codings only helped me.This is simple and Exact coding for image URL property. Thank you a lot.
Left by Sumitha on Mar 22, 2011 3:53 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
tnx very much......realy helpful 4 me....
Left by rani on Jul 02, 2011 8:39 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
image is not shown in the image control....how does that happen?? how to make it right?? used the above code

Thanks
Left by yang on Jul 12, 2011 2:26 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
Hi
image is not shown in the image control....how does that happen?? how to make it right?? used the above code

Thanks
Left by yang on Jul 12, 2011 2:38 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
Hi, thanks for this article..i used your code and its successfully run.the problem is how can i set an no image picture to the image control if the id im looking is not availbale in the database.pls help..thank you so much..
Left by Dale on Jul 26, 2011 2:25 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
I liked this article very much but i want to know one thing that if i want to display images from path in database according to selected value from Dropdownlist

Please help me for this
Left by Adeel Aslam on Aug 24, 2011 1:26 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
Thank you very much vinz, great post,

@yang,@Monika

try using a button and add the following code inside the button, it will get you the results, (But not sure whether its the best solution )

protected void Button1_Click(object sender, EventArgs e)
{

Page_Load(sender, e);
}
Left by Capt on Dec 20, 2011 1:14 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
Hi,

I was reading your article and I would like to appreciate you for making it very simple and understandable. This article gives me a basic idea of Dynamically loading image in Image control in ASP.NET and it helped me a lot. I had found another nice post over the internet which also have a wonderful explanation on Dynamically loading image in Image control in ASP.NET, for more details of that post you may visit this url...
http://www.mindstick.com/Articles/c98d98d1-3186-4cac-9069-304b08a269d3/?Dynamically%20loading%20image%20in%20Image%20control%20in%20ASP.NET

Thank you very much for your precious post.
Left by Ajay Singh on Jan 06, 2012 4:43 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
Thanks a lot for this code!!!!!!! It helped me in getting more knowledge!!!!!! Thanks
Left by Darrel on Feb 19, 2012 4:19 AM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
thanx , it helped alot
Left by mahyar on Jun 27, 2012 2:25 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
those who are facing problem in displaying the image on selection of image from DropDownList control, pls check that AutoPostBack should be set to "true" in the property of DropDownList Control.

Thanks
Left by Nitin Gupta on Aug 05, 2012 2:53 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
Thank You. It's Working.
Left by Mosam Patel on Oct 19, 2012 1:02 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
Very good lesson
thank you for posting
Left by indika on Nov 06, 2012 8:21 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
Generic Handler is not supported in .Net 1.1. Is there any workaround in .Net 1.1? Thxs in advance!
Left by Ziran on Nov 30, 2012 10:30 AM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
i need it display the image instantly its is browsed and selected ..
i,e, before i insert into the database ..
pls help me out..
Left by Bharath on Jan 02, 2013 2:48 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
its a good article.i have one problem the method defined in handler"Getconnectionstring".how to call it in web form as i am getting an error that "Getconnectionstring does not exist".have i missed something
Left by Shivani on Jan 22, 2013 2:09 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
i got my mistake ........
Left by shivani on Jan 22, 2013 3:34 PM

# re: Displaying Image to Image Control based on User Selection in ASP.NET
Requesting Gravatar...
sensible coding.........complete understanding........good work.really acknowledgeable
Left by shivani on Jan 22, 2013 4:45 PM

comments powered by Disqus

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