German Wear Discount Shop - Click Here Write for Dotnet-friends and earn for your each submission [Dot]Net-Friends
Skip Navigation Links
Home
Latest
Fast Code
Articles
Tutorials
Online Resources
Forums
Login   | Hi, Guest


Displaying Images in a Gridview using SQL Database

Written by omerkamal on Dec 28, 2006
How to display a picture in the Gridview form Database in ASP .NET 2.0

Introducation:

Displaying picture in a gridview is a different way then just using a image tag. In ASP .NET we can define a Handler to access the image from data base.

Explanation:

This Article is continuity of our Article Loading Images into SQL Server with C#. Here We will discuss about displaying a unique image for each user. This means every user will view an image he is allowed to or he have uploaded in his own profile


Article Requierments:

To make sure we undertsand the Article better, before we move next we need to make sure that we know about the following:

  • GridView/DataGrid Control
  • ASP .NET 2.0 ObjectDataSource
  • ASP .NET 2.0 Membership Objects
  • ASP .NET Generic Handlers

Now, when we made sure that we have the basic knowledge of what we will use in our article, we can go a head. Our Gridview look like this;












Instead of using BoundField we are using ItemTemplate to cerate our own customised Template. We are accessing our Images through a link which is pointing to our Handler (.ashx). So how does actually the Handler access images and present them to us? Handler process our Request and cerate a Proper Responce to it. This Responce Handling is actually what a Handler all about.


Here we will use an ObjectDataSource Object to access the current logged in user. Our ObjectDatasource Look like this:

TypeName="GetUsersData"
SelectMethod="GetUserName"
OldValuesParameterFormatString="original_{0}"/>

Here GetUsersData is our Class and GetUserName is a Static Method which brings the Current Logged-in User. To detrermin the Current Logged-in User you can use Membership and MembershipUser Objects.


We can create a Handler by right clicking on the Project > Add New Item > Select Generic Handler > Add . You can edit this newly created Handler. Now see how does our Handler look like;

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

using System;
using System.Web;
using System.IO;
using System.Configuration;

public class PicHandler : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/jpeg";
context.Response.Cache.SetCacheability(HttpCacheability.Server);
context.Response.BufferOutput = false;
// Setup the PhotoID Parameter
Stream stream = null;
string userName = context.Request.QueryString["UserName"];
if (userName != null && userName != "")
{
stream = OurUsersData.GetUserPic(userName);
if (stream == null)
{
stream = OurUsersData.GetUserPic("defaultPicture");
}

}
// Write image stream to the response stream
const int buffersize = 1024 * 16;
byte[] buffer = new byte[buffersize];
int count = stream.Read(buffer, 0, buffersize);
while (count > 0)
{
context.Response.OutputStream.Write(buffer, 0, count);
count = stream.Read(buffer, 0, buffersize);
}
}

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

Where "ourUsersData" is Class defined in the "App-code" folder and "GetUserPic" is a satic function. The bold block is showing how to get an Image. If the user did not uploaded his picture the default image will be displayed instead.


How are we accessing our Database? If you are saving images to the User Profile in ASP .NET 2.0 then you need to create a method for accessing an image from the Profile System otherwise, if you are saving Images in your own Database then you can access the database by using ADO .NET 2.0. Make sure that the return type of your Method is a Stream.

Visitors/Readers Comments
(for questions please use The Forum)



mervin
hi kamal i want a code for one of ur article. you have been developed using Generic Handler for displaying a images.. here i need a code for OurUser Data and Get UserData  

23/07/2007 01:53:13 UTC

pradeep

hai ,

thanks for giving program  .but i want something more.

My requirement is to display the images from database  into the datagrid or data view(all images).

please help me

11/01/2008 02:25:12 UTC

Primo
Thank you very much very helpful !.

16/01/2008 17:11:42 UTC

vinobaje
http://www.koffeekoder.com/ArticleDetails.aspx?id=166_Displaying_Images_in_a_GridView

25/01/2008 02:47:15 UTC

Juan

Hello,

I have a certain quantity of images saved in SQL Server 2005, what i need to do is load some images to a gridview, but the asp:imagefield only have the url where the image is, and im working with the image object loaded from the data base. If someone can help me with that i will apreciate it.

Thanks

 

26/01/2008 19:25:17 UTC

tooks
Some nice work there, you've solved a big issue for me thank you!

although there is one slight mistake which most people probably spotted straight away, but i didn't and it took me 30mins to find it, so for those people who are slow like me.

The image tag that is written like this:


Should look like this:


its just the addition of an equals sign (=).

Thanks again for the great help!

07/02/2008 04:07:36 UTC

kamal

Thanks Tooks. Now it is corrected

I appreciate your responce.

07/02/2008 05:37:03 UTC

JACK

Yaar Simple tariqe se ye kaam karo na, itna kheench taan karne ka kya jarurat hai.

Do it in an easyily understandable way.............

25/03/2008 13:58:45 UTC

JACK

Yaar Simple tariqe se ye kaam karo na, itna kheench taan karne ka kya jarurat hai.

Do it in an easyily understandable way.............

25/03/2008 14:00:28 UTC

Abdullah

Pleae make one small sample and make it downloadable

08/05/2008 00:44:59 UTC

kingston
thats correct

04/07/2008 00:19:26 UTC

jeysingh

i understand ,thank u.

04/07/2008 00:20:27 UTC

sathish
hi kamal i want a code for one of ur article. you have been developed using Generic Handler for displaying a images.. here i need a code for OurUser Data and Get UserData  

01/08/2008 00:25:02 UTC

shobha

i understand  thank u

20/08/2008 04:11:37 UTC

kapil
its good

25/11/2008 05:39:17 UTC

Bikal
public void ProcessRequest(HttpContext context)
        {
            List lstphtgallery = new List();
            lstphtgallery = PhotoGallery.Loadphotogalleries();

            for (int i = 0; i < lstphtgallery.Count; i++)
            {

                byte[] pictures = lstphtgallery[i].Picture;
                context.Response.ContentType = "image/jpeg";
                context.Response.Cache.SetCacheability(HttpCacheability.Public);
                context.Response.BufferOutput = false;
                MemoryStream membits = new MemoryStream(pictures);               
                //int bytesec = membits.Read(pictures, 0, 4096);
                //while (bytesec > 0)
                //{
                //context.Response.OutputStream.Write(pictures, 0, 4096);                  
                //bytesec = membits.Read(pictures, 0, bytesec);
                //}

                context.Response.BinaryWrite(pictures);
                context.Response.End();

            }

        }


                   
                   
                     
                                                                                                                                               
                   
               


The above is my code. I have got three pictures in database table but only one image is displayed three times in gridview. Could anyone plz help me out......

16/12/2008 05:00:12 UTC




Add your Comments

Name:  
Message:
Note: For faster response please use Forums >> for your questions instead of the comments area! (Admin)