Home > ASP.Net > Insert and Display Image from Database

Insert and Display Image from Database


try this example to Insert and Display Image from Database in Gridview

Database Script:

USE [Employee]
empname varchar(20),
empimg image


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</a>">

<html xmlns="<a href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</a>">
<head runat="server">
    <title>Save Retrieve Images</title>
    <form id="form1" runat="server">
        <asp:Label ID="lblEmpName" runat="server" Text="Employee Name"></asp:Label>
        <asp:TextBox ID="txtEName" runat="server"></asp:TextBox>
        <br />
        <asp:Label ID="lblImage" runat="server" Text="Employee Image"></asp:Label>
        <asp:FileUpload ID="imgUpload" runat="server" />
        <br />
        <br />
        <asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"
            Text="Submit" />
        <asp:Label ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>
    <br />
    <hr />
   <asp:Image ID="Image1" style="width:200px" Runat="server" />


using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

public partial class _Default : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)

    protected void btnSubmit_Click(object sender, EventArgs e)
        SqlConnection connection = null;
            FileUpload img = (FileUpload)imgUpload;
            Byte[] imgByte = null;
            if (img.HasFile && img.PostedFile != null)
                //To create a PostedFile
                HttpPostedFile File = imgUpload.PostedFile;
                //Create byte Array with file len
                imgByte = new Byte[File.ContentLength];
                //force the control to load data in array
                File.InputStream.Read(imgByte, 0, File.ContentLength);
            // Insert the employee name and image into db
            string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
            connection = new SqlConnection(conn);

            string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY";
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
            cmd.Parameters.AddWithValue("@eimg", imgByte);
            int id = Convert.ToInt32(cmd.ExecuteScalar());
            lblResult.Text = String.Format("Employee ID is {0}", id);

            // Display the image from the database
            Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;
            lblResult.Text = "There was an error";


In order to display the image on the page, we will create an Http handler. To do so, right click project > Add New Item > Generic Handler > ShowImage.ashx. Add the code shown below to the handler.


<%@ WebHandler Language="C#" Class="ShowImage" %></span></div>
<div><span style="font-size: x-small;">using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;</span></div>
<span style="font-size: x-small;">public class ShowImage : IHttpHandler
    public void ProcessRequest(HttpContext context)
       Int32 empno;
       if (context.Request.QueryString["id"] != null)
            empno = Convert.ToInt32(context.Request.QueryString["id"]);
            throw new ArgumentException("No parameter specified");

       context.Response.ContentType = "image/jpeg";
       Stream strm = ShowEmpImage(empno);
       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);

    public Stream ShowEmpImage(int empno)
        string conn = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
        SqlConnection connection = new SqlConnection(conn);
        string sql = "SELECT empimg FROM EmpDetails WHERE empid = @ID";
        SqlCommand cmd = new SqlCommand(sql,connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", empno);
        object img = cmd.ExecuteScalar();
            return new MemoryStream((byte[])img);
            return null;


    public bool IsReusable
            return false;


<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
            CellPadding="4" DataKeyNames="empid" DataSourceID="SqlDataSource1" ForeColor="#333333">
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
                <asp:BoundField DataField="empid" HeaderText="Id" InsertVisible="False" ReadOnly="True"
                    SortExpression="empid" />
                <asp:BoundField DataField="empname" HeaderText="Employee Name" SortExpression="empname" />
                <asp:TemplateField HeaderText="Employee Image" SortExpression="empimg">
                        <asp:Image ID="Image1" runat="server" Height="107px" ImageUrl='<%# Eval("empid", "~/ShowImage.ashx?id={0}") %>'
                            Width="108px" />
            <RowStyle BackColor="#EFF3FB" />
            <EditRowStyle BackColor="#2461BF" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:EmployeeConnString %>"
            ProviderName="<%$ ConnectionStrings:EmployeeConnString.ProviderName %>" SelectCommand="SELECT * FROM [EmpDetails]">

Hope it helps

Good Luck


  1. December 25, 2008 at 8:05 pm

    Awesome the whole package

  2. yasserzaid
    December 25, 2008 at 9:23 pm

    Thanks Rick for your comment

    Hope it helps you

    Best Regards,


  3. December 26, 2008 at 4:28 am

    Greate job I’ve been looking for something like this for months

    allso I’ve been playing with the new image generation
    tool take a look at my post on this forum and see if you can
    fix the problem I’m having with it and maybe you could do an articale

    i’m a novice learning along the way articales like this one are a big help I’ve allso used this code with varbinary I allso set the Image url in the Image tag on the aspx page
    I’ll keep an eye on this site for any other good stuff
    Thanks keep up the good work

  4. yasserzaid
    December 26, 2008 at 11:51 am

    Oh thank ypu Rick for you comment and i hope my blog can help you and help others also

    and i will try to post an example to explain how to insert and display image path from database and display it in Gridview

    Good Luck

    Best Regards,


  5. Laurie
    January 26, 2009 at 9:49 am

    This seems so close to what I want to do ….

    I have the addresses of the pics I want to put up as thumbnails in to a table and access the table to present them as dataview – I’d really like to have them as thumbnails and let a click present them as a full pic in a new window…….

    I’m afraid I feel comfortable at the SQL Server end – but am totally new with VB and Visual Studio.

    OKnever having ‘posted’ anything in my life, forgive me if I’m in the wrong place ……..

    the code in the asp looks like this:

    <asp:SqlDataSource ID="SqlDataSource2" runat="server"
    SelectCommand=”sp_GetPhotoURLs” SelectCommandType=”StoredProcedure”>

  6. tsatsaa
    May 29, 2011 at 5:43 am

    Thank you very much. Good luck!

  7. yasserzaid
    May 29, 2011 at 8:21 am

    @tsatsaa :- you are welcome

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: