Display Images in the Grid View Control

Steps to display images in the grid view control:

  1. Create a table schema in the following format in Sql Server

    DataGrid1.gif
     
  2. Design the web form with the following controls

    Textbox, Fileupload control, Button, Gridview, Sqldatasource

    DataGrid2.gif
     
  3. Create the sqldatasource connectionstring with the datasource property and set the datakey name to ID
     
  4. Add a Generic handler to the application(In the solution explorer right click and add select generic handler from the Templates in the New Item

It consists the code of Selecting the records from the table and displaying them in the gridview

Handler code:

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

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

public class Handler : IHttpHandler {
   
    public void ProcessRequest (HttpContext context)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        // Create SQL Command

        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "Select ImageName,Image from Images where ID =@ID";
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Connection = con;

        SqlParameter ImageID = new SqlParameter("@ID", System.Data.SqlDbType.Int);
        ImageID.Value = context.Request.QueryString["ID"];
        cmd.Parameters.Add(ImageID);
        con.Open();
        SqlDataReader dReader = cmd.ExecuteReader();
        dReader.Read();
        context.Response.BinaryWrite((byte[])dReader["Image"]);
        dReader.Close();
        con.Close();
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}