Display Images in GridView from Sql Server Database Table Using Asp.net C# VB.Net

In my previous post i showed you “How one can upload images into Sql Server using Asp.net C# FileUpload control“. In this post i will show you how one can display images into a GridView control from Sql Server table. As you know in most of the web applications requires to handle different type of images like large,thumbnail etc. If those web applications are e-commerce site then you must be carefull when handling images. In previous post i showed how you can store images & in this post i will show you how one can display images from Sql server table. The table structure is given below:

SaveImage

Displaying picture or image in a GridView is a different way then just using an image tag. In ASP.NET we can define a Handler to access the image from database. So now we need to create a Handler to read binary data from database. To do that Right click on solution explorer and Add new item, click on Generic Handler and name it ImageHandler.ashx. Write this code in ProcessRequest method:

C# Code:

    public void ProcessRequest (HttpContext context) {
        string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
        SqlConnection conn = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand();
        cmd.CommandText = "Select [Content] from Images where ID =@ID";
        cmd.CommandType = CommandType.Text;
        cmd.Connection = conn;

        SqlParameter ImageID = new SqlParameter("@ID", SqlDbType.BigInt);
        ImageID.Value = context.Request.QueryString["ID"];
        cmd.Parameters.Add(ImageID);
        conn.Open();
        SqlDataReader dReader = cmd.ExecuteReader();
        dReader.Read();
        context.Response.BinaryWrite((byte[])dReader["Content"]);
        dReader.Close();
        conn.Close();
    }

Note: Don’t forget to add “System.Configuration”, “System.Data”, “System.Data.SqlClient” namespaces.

VB.Net Code:

Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim connectionString As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
        Dim conn As New SqlConnection(connectionString)
        Dim cmd As New SqlCommand()
        cmd.CommandText = "Select [Content] from Images where ID =@ID"
        cmd.CommandType = CommandType.Text
        cmd.Connection = conn

        Dim ImageID As New SqlParameter("@ID", SqlDbType.BigInt)
        ImageID.Value = context.Request.QueryString("ID")
        cmd.Parameters.Add(ImageID)
        conn.Open()
        Dim dReader As SqlDataReader = cmd.ExecuteReader()
        dReader.Read()
        context.Response.BinaryWrite(DirectCast(dReader("Content"), Byte()))
        dReader.Close()
        conn.Close()
    End Sub

Note: Don’t forget to add “System.Configuration”, “System.Data”, “System.Data.SqlClient” namespaces.

Ok now add an aspx page in your project. Add a GridView control with a template field. Within the template field define image URL like below:

C# Code:

<asp:GridView ID="GVImages" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5">
        <Columns>
    
        <asp:BoundField DataField="Name" HeaderText="Description" />
        <asp:BoundField DataField="Type" HeaderText="Type" />
    
        <asp:TemplateField HeaderText="Image">
        <ItemTemplate>
        <asp:Image ID="Image1" runat="server" Width="200px" Height="200px" 
                   ImageUrl='<%# "ImageHandler.ashx?ID=" + Eval("ID")%>'/>
        </ItemTemplate>
        </asp:TemplateField>
    
        </Columns>        
        </asp:GridView>

VB.Net Code:

<asp:GridView ID="GVImages" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="CornflowerBlue" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White" CellPadding="5">
        <Columns>
    
        <asp:BoundField DataField="Name" HeaderText="Description" />
        <asp:BoundField DataField="Type" HeaderText="Type" />
    
        <asp:TemplateField HeaderText="Image">
        <ItemTemplate>
        <asp:Image ID="Image1" runat="server" Width="200px" Height="200px" 
                   ImageUrl='<%# "ImageHandler.ashx?ID=" + Convert.ToString(Eval("ID"))%>'/>
        </ItemTemplate>
        </asp:TemplateField>
    
        </Columns>        
        </asp:GridView>

Now everything is set except binding sql server data into the GridView. To do that write the below code in Page_Load event:

C# Code:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString;
            DataTable dt = new DataTable();
            SqlConnection conn = new SqlConnection(connectionString);
            using (conn)
            {
                SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Images", conn);
                ad.Fill(dt);
            }
            GVImages.DataSource = dt;
            GVImages.DataBind();
        }
    }

Note: Don’t forget to add “System.Configuration”, “System.Data”, “System.Data.SqlClient” namespaces.

VB.Net Code:

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim connectionString As String = ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString
            Dim dt As New DataTable()
            Dim conn As New SqlConnection(connectionString)
            Using conn
                Dim ad As New SqlDataAdapter("SELECT * FROM Images", conn)
                ad.Fill(dt)
            End Using
            GVImages.DataSource = dt
            GVImages.DataBind()
        End If
    End Sub

Note: Don’t forget to add “System.Configuration”, “System.Data”, “System.Data.SqlClient” namespaces.

Now modify the Web.Config File:

<configuration>
  <connectionStrings>
    <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
    <!--<add name="BONConnection" connectionString="Data Source=XXX.com;Initial Catalog=DBNAME;User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />-->
  </connectionStrings>
...................
...................

Note: If you use windows authentication then use the first key. Otherwise use second key line. Update server name, Database name, User name, Password as per your settings.

Now run the project & hope you will get a webpage like below:
Display Images in GridView from Sql Server Database Table Using Asp.net CSharp VB.Net

Download Code Example C#        Download Code Example VB.Net

Posted in .Net, Asp.net, C#, Database, Gridview, SQL Server, VB.Net
5 comments on “Display Images in GridView from Sql Server Database Table Using Asp.net C# VB.Net
  1. Kris says:

    Hi. How about situation when we have 2 different pictures with the same name? How can we display pictures then? Thanks for Your help.

  2. jishu says:

    Datalist have image control and checkbox.where image are retriving from databse. when i click one of row’s checkbox in datalist then other row’s image will change in datalist.How i solve it by asp.net using csharp?

  3. Erick says:

    Kris, That’s why there is an ID for that problem because the id were automatically increment each time there is a new image

    • Luciano says:

      Hi! I tried the code, when do you use the ProcessRequest? I cant fill the gridview with the Images of the DB Could you help me? Thanks!

  4. Zeeshan says:

    I am very thankful for this help

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code
     
 

*