Image from SQL using DropDownList (ASP.NET)

I was asked to create a simple webform that contains one DropDownList, filled up data from SQL and by selecting any of them show the associated image.

First of all, I’ve created the database on the SQL server (using Windows Authentication) and one table named web_Shop. The columns and data types are the following:

  • ItemNum – int
  • ItemName – varchar(50)
  • Cost – int
  • Count – int
  • Images – image

Yes, I know there’s no primary key, but this was the request (as well as all the columns can have NULL value…). I suggest you to insert one more column named ID – int (Primary Key, auto increment).

One of the main difference between ComboBox and DropDownList that if you set the DataSource to your custom type list, the selected item cannot be cast to your object when using DropDownList.

List<MyObject> obj = new List<MyObject>();
//... add some items to the list
comboBox1.DataSource = obj;
dropDownList1.DataSource = obj;

Now this will work with ComboBox:

(comboBox1.SelectedItem as MyObject).FullName

… but won’t work with DropDownList. You have to set the DataValueField and the DataTextField of the DropDownList.

dropDownList1.DataValueField = "ID";//this will be the SelectedItem
dropDownList1.DataTextField = "FullName";//this will be the text of the DropDownList

Now, let’s create the simpliest class (WebShop.cs) for the SQL table:

public class WebShop
{
    int itemNum;
    string itemName;
    int cost;
    int count;
    
    public int ItemNum
    {
        get { return itemNum; }
        set { itemNum = value; }
    }

    public string ItemName
    {
        get { return itemName; }
        set { itemName = value; }
    }

    public int Cost
    {
        get { return cost; }
        set { cost = value; }
    }

    public int Count
    {
        get { return count; }
        set { count = value; }
    }

    public WebShop(int _itemNum, string _itemName, int _cost, int _count)
    {
        ItemNum = _itemNum;
        ItemName = _itemName;
        Cost = _cost;
        Count = _count;
    }
}

Now we have to show the image. Let’s use some handler. Create our own handler (PhotoHandler.ashx), implementing IHttpHandler interface:

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

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;

public class PhotoHandler : IHttpHandler
{

    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext ctx)
    {
        string num = ctx.Request.QueryString["num"];
        if (num == null) throw new ArgumentException("Missing parameter!");

        SqlConnection conn = new SqlConnection("Data Source=tcp:localhost,1433;Integrated Security=True;Encrypt=True;TrustServerCertificate=True;PersistSecurityInfo=True;database=cauamhoton;connection timeout=30;Pooling=False");
        SqlCommand cmd = new SqlCommand("SELECT Images FROM web_Shop WHERE ItemNum=@num", conn);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.Add("@num", num);

        try
        {
            if (conn.State != ConnectionState.Open) conn.Open();
            byte[] pict = (byte[])cmd.ExecuteScalar();
            if (conn.State != ConnectionState.Closed) conn.Close();

            ctx.Response.ContentType = "image/jpg";
            ctx.Response.OutputStream.Write(pict, 0, pict.Length);
        }
        catch (Exception)
        {
            //throw;//this exception throws when you try to open the PhotoHandler.ashx without num parameter!
        }
    }
}

Now we are ready to create the main webform, named Default.aspx. Add one asp:DropDownList and a simple html img tag

<img id="img" runat="server" width="200" height="200" />

Yes. It’s not really XHTML5 valid because of the missing ‘src’ tag of the ‘img’. This will be ‘handled’.
The code-behind of the Default.aspx:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Imaging;
using System.IO;
using System.Web.UI;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection conn;
    List webShopItems;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            conn = new SqlConnection("Data Source=tcp:localhost,1433;Integrated Security=True;Encrypt=True;TrustServerCertificate=True;PersistSecurityInfo=True;database=cauamhoton;connection timeout=30;Pooling=False");//this connection string uses Windows Authentication on your SQL server and default port number: 1433. Change 'localhost' to the IP address or the host name of your SQL sever
            webShopItems = new List();

            DownloadFromSql();
        }
        else
        {
            if (DropDownList1.SelectedIndex != -1)
            {
                img.Src = "PhotoHandler.ashx?num=" + DropDownList1.SelectedValue;
            }
        }
    }

    private void DownloadFromSql()
    {
        try
        {
            if (conn.State != ConnectionState.Open) conn.Open();
            SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM web_Shop", conn);
            DataTable dt = new DataTable();
            da.Fill(dt);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                //Because you allow the NULL in sql, you have to check if a column contains null!
                if (dt.Rows[i]["ItemNum"] != DBNull.Value && dt.Rows[i]["Cost"] != DBNull.Value && dt.Rows[i]["Count"] != DBNull.Value)
                {
                    WebShop item = new WebShop((int)dt.Rows[i]["ItemNum"], dt.Rows[i]["ItemName"].ToString(), (int)dt.Rows[i]["Cost"], (int)dt.Rows[i]["Count"]);
                    webShopItems.Add(item);
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (conn.State == ConnectionState.Open) conn.Close();
            DropDownList1.DataSource = webShopItems;
            DropDownList1.DataValueField = "ItemNum";//what the selectedvalue will be when selecting an item
            DropDownList1.DataTextField = "ItemName";//what you see in dropdownlist
            DropDownList1.DataBind();

        }
    }
}