Thursday, November 1, 2012

Display Images In GridView From DataBase Asp.Net

In this example i am explaining how to Show Display Images In GridView From DataBase In ASP.NET Using C# And VB.NET or showing images stored or saved in SQL Server database in gridview,For this i've already stored images in Database.

Table schema is shown below, ID column is primary key with Identity increment,datatype of Image column is Binary.


Display Images In GridView From DataBase Asp.Net
To know how to save or store Images in DataBase visit link below

Upload/Save Images in Database using FileUpload Control in ASP.NET C# VB.NET


For displaying images in gridview we need to create a Handler to read binary data from database.
Right click on solution explorer and Add new item, Pick Generic Handler and name it Handler.ashx.
Write this code in ProcessRequest method
C# code behind
<%@ 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();
}

VB.NET Code
Public Class Handler
    Implements IHttpHandler
    
Public Sub ProcessRequest(ByVal context As HttpContext)
Dim con As New SqlConnection()
con.ConnectionString = ConfigurationManager.ConnectionStrings
                        ("ConnectionString").ConnectionString
        
        ' Create SQL Command 
        
        Dim cmd As New SqlCommand()
        cmd.CommandText = "Select ImageName,Image from Images" +
                          " where ID =@IID"
        cmd.CommandType = System.Data.CommandType.Text
        cmd.Connection = con
        
        Dim ImageID As New SqlParameter
                             ("@IID", System.Data.SqlDbType.Int)
        ImageID.Value = context.Request.QueryString("ID")
        cmd.Parameters.Add(ImageID)
        con.Open()
        Dim dReader As SqlDataReader = cmd.ExecuteReader()
        dReader.Read()
        context.Response.BinaryWrite
                    (DirectCast(dReader("Image"), Byte()))
        dReader.Close()
        con.Close()
    End Sub
End Class

Now drag a GridView control on the aspx page and add SQLDataSource to it.

For configuring GridVIew with SqlDataSource read
Insert Delete Update records in GridView using SqlDataSource ItemTemplate and EditItemTemplate

Now go to html markup of GridView and add a TemplateField and in ItemTemplate add a Image control to display Images.
Html Source of GridView should look like this
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" DataKeyNames="ID"
              DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" 
                InsertVisible="False" ReadOnly="True"
                               SortExpression="ID" />
<asp:BoundField DataField="ImageName" HeaderText="ImageName" 
                               SortExpression="ImageName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" 
           ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [ImageName], [Image] 
              FROM [Images]"></asp:SqlDataSource>

For VB.NET there is slight change in html markup of page
change below mentioned line
ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/>

to

ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}")%>'/>

THis is how it will look

If you want to display Images in multiple columns or in more than one clumns of GridView then u need to make changes in the code as mentioned below.

1. Add a new column in database (i've named it Image2)
2. Add one mote Template Field in html source of gridview and change source as below
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" 
ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}")+"&img=1"%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image2">
<ItemTemplate>
<asp:Image ID="Image2" runat="server" 
ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}")+"&img=2"%>'/>
</ItemTemplate>
</asp:TemplateField>

And make these changes in code behind of handler.ashx
//Add this line of code in handler.ashx
int intImg = Convert.ToInt32(context.Request.QueryString["img"]);
//Now change earlier code to this one 
SqlDataReader dReader = cmd.ExecuteReader();
        dReader.Read();
        if (intImg == 1)
        {
            context.Response.BinaryWrite((byte[])dReader["Image"]);
        }
        else if (intImg == 2)
        {
            context.Response.BinaryWrite((byte[])dReader["Image2"]);
        }
        dReader.Close();
        con.Close();
Now it will look like this


hope this helps.

Download sample code attached

Sample code for displaying Images in Multiple columns




Other GridView articles:
ASP.NET Display Images in Gridview/DataList using objectdatasource

ASP.NET Insert Edit Update GridView with ObjectDataSource

Add AutoNumber Column in GridView or DataList

Creating Shopping cart in ASP.NET C# VB.NET Example using DataList GridView

Ajax autocomplete extender textbox in EditItemTemaplate of GridView

3 comments:

  1. Thank you!! I was converting VB to C# and I needed this:
    "For VB.NET there is slight change in html markup of page
    change below mentioned line... "
    You are a lifesaver!

    ReplyDelete