.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> ASP.NET >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Display image in gridview

Posted By:Pankaj Mishra       Posted Date: January 07, 2010    Points: 25    Category: ASP.NET    URL: http://www.dotnetspark.com  
 

Display image in gridview

In this article we will see how to display image in a gridview from and folder reside in serve and images from database (SQL Server).

In both the case we need a Template column in a gridview and add html image (img) tag in it. you can also take asp.net image control but it will generate view state so we have taken html img tag.

if you are using asp.net image control than i would suggest that make the EnableViewState property of image control to false.

Lets see the 1st scenario

Display Picture in a GridView from Database

let's 1st create a table and call it as Image_Table to create sample table below is the code. Here I am using Image data type of SQL server to save image into it. As we all know that SQL Server store Image as binary data in a column of datatype IMAGE.

CREATE TABLE [dbo].[Image_Table](
 [id] [int] IDENTITY(1,1) NOT NULL,
 [SomeText] [varchar](50) NULL,
 [ImagePath] [varchar](200) NULL,
 [Image_Blob] [image] NULL,
 CONSTRAINT [PK_Image_Table] PRIMARY KEY CLUSTERED 
(
 [id] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Here is the table schema in figure


Now Create one stored procedure to fetch data from database and bind that to GridView

CREATE PROCEDURE GetImageInfoFromDB
AS 
BEGIN 

 SELECT  id,SomeText,ImagePath,Image_Blob FROM dbo.Image_Table 

END

In this example we are using HTTPHandler to fetch Images from Database. For that I have created another stored procedure which will accept one input parameter id

CREATE PROCEDURE GetImageFromDB(@id int)
AS 
BEGIN 

 SELECT  id,SomeText,ImagePath,Image_Blob FROM dbo.Image_Table WHERE id = @id

END

I assume that some data is available into the table

To add HTTPHandler right click on the project explorer --> AddNewItem --> Generic Handler from the templete eg given pic below and Name it as ImageHanlder.ashx

Now in you HTTPHandler you can add this lines of code

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

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


public class ImageHandler : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {
        string strId = context.Request.QueryString["Id"];

        if (!string.IsNullOrEmpty(strId))
        {
            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
            SqlDataReader sqlDr = null;
            try
            {
                conn.Open(); //open database connection

                SqlCommand sqlCmd = new SqlCommand("GetImageFromDB", conn);
                sqlCmd.CommandType = CommandType.StoredProcedure; 
                
                //Add the parameter to SQLCommand object
                sqlCmd.Parameters.AddWithValue("@id", strId);

                sqlDr = sqlCmd.ExecuteReader();

                sqlDr.Read();

                context.Response.BinaryWrite((Byte[])sqlDr[3]);

                context.Response.End();
                
                
            }
            catch (Exception ex)
            {
                //Handle error If occured
            }
            finally
            {
                if (sqlDr != null && !sqlDr.IsClosed)
                {
                    sqlDr.Close(); //close SqlDataReader
                }
                conn.Close();//close database connection
            }
        }

    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

Now in you page in which gridView is there your code should look like this after adding templete column

 
        
            
            
                
                    Image
                
            
        
    

Now to bind data in a gridview you can add below lines of code in any event in which you want like Page Load event, Button Click event etc.

In C# example

private void LoadData()
{

        string returnValue = string.Empty;

        //Get the databse connection string from web.config file
        string conString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

        SqlConnection sqlConn = new SqlConnection(conString);
        SqlDataReader sqlDr = null;
        try
        {
            //Call the stored procedure using SQLDataAdapter
            SqlDataAdapter salDa = new SqlDataAdapter("GetImageInfoFromDB", sqlConn);
            
            DataSet ds = new DataSet();
            salDa.Fill(ds);   // Fill the dataset 

            //Bind the data which in form of dataset to ggridview
            GridView1.DataSource = ds;
            GridView1.DataBind();

        }
        catch (Exception ex)
        {
            //Handle Error if any occured
        }
        finally
        {
            if (sqlDr != null && !sqlDr.IsClosed)
            {
                sqlDr.Close(); //close sqldatareader
            }
            //Close SQL connection
            sqlConn.Close();
        }

}

In VB.NET sample code

Private Sub LoadData()
    
    Dim returnValue As String = String.Empty
    
    'Get the databse connection string from web.config file
    Dim conString As String = ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString
    
    Dim sqlConn As New SqlConnection(conString)
    Dim sqlDr As SqlDataReader = Nothing
    Try
        'Call the stored procedure using SQLDataAdapter
        Dim salDa As New SqlDataAdapter("GetImageInfoFromDB", sqlConn)
        
        Dim ds As New DataSet()
        salDa.Fill(ds)
        ' Fill the dataset 
        'Bind the data which in form of dataset to ggridview
        GridView1.DataSource = ds
            
        GridView1.DataBind()
    Catch ex As Exception
        'Handle Error if any occured
    Finally
        If sqlDr IsNot Nothing AndAlso Not sqlDr.IsClosed Then
                'close sqldatareader
            sqlDr.Close()
        End If
        'Close SQL connection
        sqlConn.Close()
        
    End Try
End Sub

If you run the application you can see in image in gridview like this

Display Image in a GridView from server folder

Here is how your gridview will look like it has one bound column and one Template column. In the template column of gridview I am going to add HTML Img tag for displaying images.

Here i assume that you have a folder called image in the root folder of the application and all the images contain in it. Also the path of the images is available into one column of the database

 
        
            
            
                
                    Image
                
            
        
    

Now in the server side in .cs or vb file

private void LoadData()
{

        string returnValue = string.Empty;
        //Get the databse connection string from web.config file
        string conString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;

        SqlConnection sqlConn = new SqlConnection(conString);
         SqlDataReader sqlDr = null;
        try
        {

            SqlCommand sqlCmd = new SqlCommand("GetImageInfoFromDB", sqlConn);

            sqlCmd.CommandType = CommandType.StoredProcedure;

            sqlConn.Open();

            sqlDr = sqlCmd.ExecuteReader();

            //Bind gridView
            GridView2.DataSource = sqlDr; 
            GridView2.DataBind();

        }
        catch(Exception ex)
        {
            //Handle Error
        }
        finally
        {
            if (sqlDr != null && !sqlDr.IsClosed)
            {
                sqlDr.Close(); //close sqldatareader
            }

            sqlConn.Close();
        }

}

Same above code in VB.Net

 

Private Sub LoadData()
    
    Dim returnValue As String = String.Empty
    'Get the databse connection string from web.config file
    Dim conString As String = ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString
    
    Dim sqlConn As New SqlConnection(conString)
    Dim sqlDr As SqlDataReader = Nothing
    Try
        
        Dim sqlCmd As New SqlCommand("GetImageInfoFromDB", sqlConn)
        
        sqlCmd.CommandType = CommandType.StoredProcedure
        
        sqlConn.Open()
        
        sqlDr = sqlCmd.ExecuteReader()
        
        'Bind gridView
        GridView2.DataSource = sqlDr
            
        GridView2.DataBind()
    Catch ex As Exception
        'Handle Error
    Finally
        If sqlDr IsNot Nothing AndAlso Not sqlDr.IsClosed Then
                'close sqldatareader
            sqlDr.Close()
        End If
        
        sqlConn.Close()
        
    End Try
End Sub

Now if you run the application you can see the picture is displaying from the server folder

You can also download the sample project by clicking the below download link. This sample project contains both the scenario to display picture in you asp.net application. You can also display thumbnail image in a gridview like above manner

Hope this will help all

Cheers!!!
Pankaj
 


 Subscribe to Articles

     

Further Readings:

Responses
Author: Hwee         Company URL: http://www.dotnetspark.com
Posted Date: December 16, 2010

I used your sample code. The only different is my table has 4 fields as bellow:

field dataType
ID int
userID int
ImageData varbinary(MAX)
DateUploaded datetime

Problem that I am experiencing is: Sample photo display on the report. In my table, I have two different photos but on the report, two rows return and have the right info for ID, userID and DateUploaded but not the photo. Same photo displays (2 rows) in the report intead of different photo. Not sure why. Do you have any clue? If you have a minute, could you response to my post? Thanks

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend