Search
Close this search box.

Displaying Image to Image Control based on User Selection in ASP.NET

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 on 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 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.

STEP1: 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 a Handler file.

STEP2: 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

STEP3: 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.

STEP4: 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.

STEP5: Displaying the Image based on the value selected from the DropDownList

Here’s the codes 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! Hope you will find this example useful!

This article is part of the GWB Archives. Original Author: Vinz’s Blog

Related Posts