Glen Robson

Glen Robson

  • NA
  • 46
  • 21.9k

Product List Image

Nov 4 2011 10:33 AM

Hi guys,

I have recently been teacing myself .NET C# and i am currently working on a project to create an ecommerce site just as a learning experience more than anything.

I have created most of the site already however i have came accross with creating the product list (Gallery).

I would like to have a list of the products in my database to show on the screen with an image of each product. I have tried to do this several ways with no success. Below shows how my database is set out and also shows the code i am using. The problem i am having is showing the images of each product. I think the reason the image is not showing is due to the fact that i am creating the <asp:Image> tag in the code behind so therefore this can not pick up my Image Handler. IT will make more sence when you see my code:

Microsoft SQL Server
[U][B]Database:[/B][/U]

[B]Product[/B]
Product_id - Numeric
name - Varchar
Descr - Varchar
Price - Varchar
Quantity - Numeric
Brand - Varchar
Gender - Varchar
Image - Image

[U][B]Code:[/B][/U]

[B]Products.aspx.cs[/B]

[CODE]

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.IO;

namespace WebApplication1
{
    public partial class Products : System.Web.UI.Page
    {

        string connectionString =
            WebConfigurationManager.ConnectionStrings["Test_1"].ConnectionString;

        #region LoadProducts
        protected void Page_Load(object sender, EventArgs e)
        {

            /* SqlConnection conn = new SqlConnection(connectionString);
           conn.Open();

           SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Product", conn);
           DataTable dt = new DataTable();
           da.Fill(dt);
           conn.Close();

           listView.DataSource = dt;
           listView.DataBind(); */

           
            lblResult.Text = "";

            // Create a Select statement that searches for a record
            // matching the specific author ID from the Value property.
            string selectSQL;
            selectSQL = "SELECT * FROM Product ";
            selectSQL += "WHERE Gender=@Gender";
            // Define the ADO.NET objects.
            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand(selectSQL, con);
            SqlDataReader reader;

            cmd.Parameters.AddWithValue("@Gender ", lstProducts.Text);
            // Try to open database and read information.
            try
            {

                con.Open();
                reader = cmd.ExecuteReader();
                while (reader.Read())
                {

                   
 
                    // Build a string with the record information,
                    // and display that in a label.
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    sb.Append("<b>");
                    sb.Append(reader["name"]);
                    sb.Append("</b><br /> ");
                    sb.Append("Description: ");
                    sb.Append(reader["Descr"]);
                    sb.Append("<br />");
                    sb.Append("Price: ");
                    sb.Append(reader["Price"]);
                    sb.Append("<br />");
                    sb.Append("Quantity: ");
                    sb.Append(reader["Quantity"]);
                    sb.Append("<br />");
                    sb.Append("Brand: ");
                    sb.Append(reader["Brand"]);
                    sb.Append("<br />");
                    sb.Append("Gender: ");
                    sb.Append(reader["Gender"]);
                    sb.Append("<asp:Image ID='test' runat='server' ImageUrl='~/ImgHandler.ashx?id="+ reader["Product_id"].ToString() +"' />");
                    sb.Append("<br />");
                    sb.Append("<br />");


                    lblResult.Text += sb.ToString();
                }
                reader.Close();

               
            }
            catch (Exception err)
            {
                lblResult.Text = "Error getting author. ";
                lblResult.Text += err.Message;
            }
            finally
            {
                con.Close();
            }

        }
        #endregion
       
        #region Fill_Dropdown
        private void FillProductList()
        {

            string selectSQL = "SELECT name, Price, Product_id FROM Product";
            SqlConnection con = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand(selectSQL, con);
            SqlDataReader reader;

            // Try to open database and read information.
            try
            {
                con.Open();
                reader = cmd.ExecuteReader();
                // For each item, add the author name to the displayed
                // list box text, and store the unique ID in the Value property.
                while (reader.Read())
                {
                    ListItem newItem = new ListItem();
                    newItem.Text = reader["name"] + ", " + reader["Price"];
                    newItem.Value = reader["Product_id"].ToString();
                    lstProducts.Items.Add(newItem);
                }
                reader.Close();
            }
            catch (Exception err)
            {
                lblResult.Text = "Error reading list of names. ";
                lblResult.Text += err.Message;
            }
            finally
            {
                con.Close();
            }


        }

        #endregion

    }
}

[/CODE]

[B]ImgHandler.ashx[/B]

[CODE]using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.IO;
using System.Configuration;


namespace WebApplication1
{
    /// <summary>
    /// Summary description for ImgHandler
    /// </summary>
    public class ImgHandler : IHttpHandler
    {
        string connectionString =
            WebConfigurationManager.ConnectionStrings["Test_1"].ConnectionString;

        public void ProcessRequest(HttpContext context)
        {
           
            Int32 prodno;
            if (context.Request.QueryString["id"] != null)
                prodno = Convert.ToInt32(context.Request.QueryString["id"]);
            else
                throw new ArgumentException("No parameter specified");

            context.Response.ContentType = "image/jpeg";
            Stream strm = ShowProdImage(prodno);
            byte[] buffer = new byte[4096];
            int byteSeq = strm.Read(buffer, 0, 4096);

            while (byteSeq > 0)
            {
                context.Response.OutputStream.Write(buffer, 0, byteSeq);
                byteSeq = strm.Read(buffer, 0, 4096);
            }
            //context.Response.BinaryWrite(buffer);

        }


        public Stream ShowProdImage(int prodno)
        {

            SqlConnection con = new SqlConnection(connectionString);

            string sql = "SELECT Image FROM Product WHERE Product_id = @ID";
            SqlCommand cmd = new SqlCommand(sql, con);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@ID", prodno);
            con.Open();
            object img = cmd.ExecuteScalar();
            try
            {
                return new MemoryStream((byte[])img);
            }
            catch
            {
                return null;
            }
            finally
            {
                con.Close();
            }
        }
            


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

    }
}[/CODE]



Any help would be appreciated.

Thanks Boldonglen

Answers (22)