Create a Picture Album using ListView in ASP.NET 3.5

Posted by: Suprotim Agarwal , on 7/17/2008, in Category ASP.NET
Views: 195391
Abstract: In this article, we will see how to create a Picture Album using the ListView control. We will explore the GroupTemplate of ListView and explore how we can group multiple images together in the ListView, thereby creating an album effect.
Create a Picture Album using ListView in ASP.NET 3.5
 
In this article, we will see how to create a Picture Album using the ListView control. We will explore the GroupTemplate of ListView and explore how we can group multiple images together in the ListView, thereby creating an album effect.
In one of the previous articles Save and Retrieve Images from the Database using ASP.NET 2.0 and ASP.NET 3.5 we had discussed how to use image handlers to save and retrieve images in the database. In this article, we will build on that concept and use the same technique to display images in a ListView.
We will learn how to upload an image and then display the uploaded image on the same page in an ‘album mode’ using the ListView. At the end of this article, you will also learn how to use the different templates of a ListView. If you are unfamiliar with the ListView control, I suggest you to read my article Exploring the ListView control in ASP.NET 3.5 to get an understanding of the same. To keep the article simple and easy to understand, I have not covered any validations associated with image control or other control. The article also does not suggest you best practices. In this article, we will only discuss how to read images from the database and display it in the ListView control, and that would be the focus for this article.  I assume you have some knowledge of creating ASP.NET 3.5 websites. We will be using Visual Studio 2008.
Let us start off by first creating a sample database and adding a table to it. We will call the database ‘PictureAlbum’ and the table will be called ‘Album’. This table will contain an image column along with some other columns. Run the following script in your SQL 2005 Query window (or server explorer) to construct the database and the table.
CREATE DATABASE [PictureAlbum]
GO
USE [PictureAlbum]
GO
CREATE TABLE Album
(
pic_id int IDENTITY NOT NULL,
picture_tag varchar(50),
pic image
)
Step 1: Create a new ASP.NET website. In the code-behind, add the following namespace
C#
using System.Data.SqlClient;
VB.NET
Imports System.Data.SqlClient
Step 2: Drag and drop two label and one textbox control. Also drag drop a FileUpload control and a button control to upload the selected image on button click. As mentioned earlier, there are no validations performed. The source would look similar to the following:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Image
        <asp:Label ID="lblTags" runat="server" Text="Tags"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="txtTags" runat="server"></asp:TextBox>
        <br />
        <asp:Label ID="lblImage" runat="server" Text="Upload Picture"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:FileUpload ID="imgUpload" runat="server" />
        <br />
        <br />
        <asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"
            Text="Submit" />  
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp<asp:Label ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>
    <br />
    <hr />
    </div>
 
    </form>
</body>
</html>
 
Also in the web.config, add a <connectionStrings> tag as displayed below:
<connectionStrings>
 <add name="albumConnString" connectionString="Data Source=(local); Initial Catalog = PictureAlbum; Integrated Security=True;"providerName="System.Data.SqlClient" />
 </connectionStrings>
Step 3: In the button click event, add the following code:
C#
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        SqlConnection connection = null;
        try
        {
            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 picture tag and image into db
            string conn = ConfigurationManager.ConnectionStrings["albumConnString"].ConnectionString;
            connection = new SqlConnection(conn);
 
            connection.Open();
            string sql = "INSERT INTO Album(picture_tag,pic) VALUES(@tag,@pic) SELECT @@IDENTITY";
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.AddWithValue("@tag", txtTags.Text);
            cmd.Parameters.AddWithValue("@pic", imgByte);
            int id = Convert.ToInt32(cmd.ExecuteScalar());
            lblResult.Text = String.Format("Picture ID is {0}", id);
        }
        catch
        {
            lblResult.Text = "There was an error";
        }
        finally
        {
            connection.Close();
        }
    }
VB.NET
      Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
            Dim connection As SqlConnection = Nothing
            Try
                  Dim img As FileUpload = CType(imgUpload, FileUpload)
                  Dim imgByte As Byte() = Nothing
                  If img.HasFile AndAlso Not img.PostedFile Is Nothing Then
                        'To create a PostedFile
                        Dim File As HttpPostedFile = imgUpload.PostedFile
                        'Create byte Array with file len
                        imgByte = New Byte(File.ContentLength - 1){}
                        'force the control to load data in array
                        File.InputStream.Read(imgByte, 0, File.ContentLength)
                  End If
                  ' Insert the picture tag and image into db
                  Dim conn As String = ConfigurationManager.ConnectionStrings("albumConnString").ConnectionString
                  connection = New SqlConnection(conn)
 
                  connection.Open()
                  Dim sql As String = "INSERT INTO Album(picture_tag,pic) VALUES(@tag,@pic) SELECT @@IDENTITY"
                  Dim cmd As SqlCommand = New SqlCommand(sql, connection)
                  cmd.Parameters.AddWithValue("@tag", txtTags.Text)
                  cmd.Parameters.AddWithValue("@pic", imgByte)
                  Dim id As Integer = Convert.ToInt32(cmd.ExecuteScalar())
                  lblResult.Text = String.Format("Picture ID is {0}", id)
            Catch
                  lblResult.Text = "There was an error"
            Finally
                  connection.Close()
            End Try
      End Sub
 
In the code above, we are creating a byte array equal to the length of the file. The byte array will store the image. We then load the image data into the array. The record containing the Picture Tags and Image is then inserted into the database using the ADO.NET code. The ID inserted is returned back using the @@Identity. We will shortly use this ID and pass it as a query string parameter to the ShowImage handler. The image will then be fetched against the Picture ID (pic_id). If you run the application as of now, you should be able to upload the images to the database.
Step 4: 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. In the code shown below, we are using the Request.QueryString[“id”] to retrieve the PictureID(pic_id) from the handler url. The ID is then passed to the ‘ShowAlbumImage()’ method where the image is fetched from the database and returned in a MemoryStream object. We then read the stream into a byte array. Using the OutputStream.Write(), we write the sequence of bytes to the current stream and you get to see your image.
C#
<%@ WebHandler Language="C#" Class="ShowImage" %>
 
using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;
 
public class ShowImage : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        Int32 picid;
        if (context.Request.QueryString["id"] != null)
            picid = Convert.ToInt32(context.Request.QueryString["id"]);
        else
            throw new ArgumentException("No parameter specified");
 
        context.Response.ContentType = "image/jpeg";
        Stream strm = ShowAlbumImage(picid);
        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);
        }
        //context.Response.BinaryWrite(buffer);
    }
 
    public Stream ShowAlbumImage(int picid)
    {
        string conn = ConfigurationManager.ConnectionStrings["albumConnString"].ConnectionString;
        SqlConnection connection = new SqlConnection(conn);
        string sql = "SELECT pic FROM Album WHERE Pic_ID = @ID";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", picid);
        connection.Open();
        object img = cmd.ExecuteScalar();
        try
        {
            return new MemoryStream((byte[])img);
        }
        catch
        {
            return null;
        }
        finally
        {
            connection.Close();
        }
    }
 
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
 
 
}
VB.NET
<%@ WebHandler Language="vb" Class="ShowImage" %>
 
Imports System
Imports System.Configuration
Imports System.Web
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
 
Public Class ShowImage
      Implements IHttpHandler
      Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
            Dim picid As Int32
            If Not context.Request.QueryString("id") Is Nothing Then
                  picid = Convert.ToInt32(context.Request.QueryString("id"))
            Else
                  Throw New ArgumentException("No parameter specified")
            End If
 
            context.Response.ContentType = "image/jpeg"
            Dim strm As Stream = ShowAlbumImage(picid)
            Dim buffer As Byte() = New Byte(4095){}
            Dim byteSeq As Integer = strm.Read(buffer, 0, 4096)
 
            Do While byteSeq > 0
                  context.Response.OutputStream.Write(buffer, 0, byteSeq)
                  byteSeq = strm.Read(buffer, 0, 4096)
            Loop
            'context.Response.BinaryWrite(buffer);
      End Sub
 
      Public Function ShowAlbumImage(ByVal picid As Integer) As Stream
            Dim conn As String = ConfigurationManager.ConnectionStrings("albumConnString").ConnectionString
            Dim connection As SqlConnection = New SqlConnection(conn)
            Dim sql As String = "SELECT pic FROM Album WHERE Pic_ID = @ID"
            Dim cmd As SqlCommand = New SqlCommand(sql, connection)
            cmd.CommandType = CommandType.Text
            cmd.Parameters.AddWithValue("@ID", picid)
            connection.Open()
            Dim img As Object = cmd.ExecuteScalar()
            Try
                  Return New MemoryStream(CType(img, Byte()))
            Catch
                  Return Nothing
            Finally
                  connection.Close()
            End Try
      End Function
 
      Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
            Get
                  Return False
            End Get
      End Property
 
 
End Class
 
Step 5: We will now add the ListView to our page. We will see how to use the ‘GroupTemplate’ to display images in multiple columns (in our case 4 images). Add a SQLDataSource control to the page. After configuring it with the database, the code will look similar to the following
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:albumConnString %>"
        ProviderName="System.Data.SqlClient"
        SelectCommand="SELECT [pic_id],picture_tag, [pic] FROM [Album]"></asp:SqlDataSource>
Now add a ListView Control to the page and set its DataSource property to ‘SqlDataSource1’. After adding the LayoutTemplate, ItemTemplate and GroupTemplate the code will look similar to the following:
    <asp:ListView ID="ListView1" GroupItemCount="4" runat="server" DataKeyNames="pic_id"
    DataSourceID="SqlDataSource1">
        <LayoutTemplate>
            <asp:Placeholder
            id="groupPlaceholder"
            runat="server" />
        </LayoutTemplate>
        <GroupTemplate>
            <div>
            <asp:Placeholder
            id="itemPlaceholder"
            runat="server" />
            </div>
        </GroupTemplate>
        <ItemTemplate>
            <asp:Image
            id="picAlbum" runat="server" AlternateText='<% #Eval("picture_tag") %>'
            ImageUrl='<%# "ShowImage.ashx?id=" + Eval("pic_id") %>' />
        </ItemTemplate>
        <EmptyItemTemplate>           
           
        </EmptyItemTemplate>
    </asp:ListView>
If you observe, the <LayoutTemplate> contains a placeholder called ‘groupPlaceholder’. When the page is rendered, the groupPlaceholder is replaced with the contents of GroupTemplate. Similarly, the <GroupTemplate> includes the ‘itemPlaceholder’ placeholder. The itemPlaceholder is replaced with the contents of the ItemTemplate, which is an image. As you know, the <ItemTemplate> renders each time there is an item from the source. The ‘GroupItemCount’ attribute decides the number of items displayed in a <GroupTemplate> before a new row is created. Here we have set the ImageUrl to an expression which makes a call to the handler and displays the images from the database. In the code below, we pass the pic_id as a query string parameter to the Http Handler. Similarly the tags entered by you are shown as alternate text on the images. To see the text, hover your mouse over the image, when the application is run.
 
Note: One last thing. In order to display images as they are added, just add this line of code (ListView1.DataBind()) in the btnSubmit_Click, just before the try block ends.
 
...
lblResult.Text = String.Format("Picture ID is {0}", id);
ListView1.DataBind();
 
We are all set. It’s time to you run the application!! Start uploading images and you will observe that as you upload the images, the gallery gets updated and the image is displayed in an album mode using the ListView control as shown below:
 
List View
 
The source code for this article in C# and VB.NET can be downloaded from here. I hope you liked the article and I thank you for viewing it.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.

Get in touch with him on Twitter @suprotimagarwal or at LinkedIn



Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by jordan on Tuesday, July 22, 2008 4:28 PM
Nice demo, i am trying to do it with an objectdatasource we will see how it goes.
Comment posted by md.tahir1 on Friday, August 1, 2008 1:53 AM
i want create crystal report in vb.net 3.5. some combo boxes in search criteria & value print in crystal report these combo boxes.
and fetch record by sql statement in crystal report.

plzz help me
Comment posted by Ajay on Thursday, September 4, 2008 10:24 AM
Very good article. ListView control is powerful indeed. I really liked the GroupItemCount property -- so no more variables to count the items in the code.
Comment posted by Hoffman on Tuesday, September 9, 2008 12:57 PM
I enjoyed reading it. Thanks for the step by step approach.
Comment posted by Anton on Tuesday, September 9, 2008 1:43 PM
Please put some energy in your code if posting it as a turtorial.
Comment posted by om on Tuesday, September 9, 2008 7:40 PM
short and nice article.
Comment posted by Suprotim Agarwal on Tuesday, September 9, 2008 9:39 PM
Ajay, Hoffman, Om: Thanks.

Anton: Thanks for your comments. Was there are anything in the article that was not clear enough?
Comment posted by Scott on Tuesday, September 9, 2008 9:57 PM
Thank you for the article in both C# and VB.  These article are far too often only done in C# these days.  I now have an example of the HTTPHandler in VB that I needed. Thanks
Comment posted by Abdul ajees on Wednesday, September 10, 2008 12:24 AM
Its very usefull atricle ....
Thanks

Comment posted by winfidel on Wednesday, September 10, 2008 6:41 AM
I am interested in designing a game like Torn City or Beyond 3volution only the game educates and does not insist on violence as a solution to every problem. I was looking in to programs for a simple database .. something where each person who signs in has access to certain areas based on their experience level and stats... so they would have to earn stats. I like the idea of different locations on the island shown with pictures, items found saved to their possessions, their hut purchased through income earned... all these factors I have to have set up. Which program should I use to try and design this game?
Comment posted by Suprotim Agarwal on Wednesday, September 10, 2008 1:00 PM
Scott, Abdul: Thanks for the kind words. We at dotnetcurry treat a language(c# or vb.net) nothing more than a tool to achieve the functionality. What really matters is that the requirement should be achieved in the best possible way and using the best technology. In most of our future articles too, we will provide code in both C# and VB.NET. Thanks.

winfidel: Find an interesting discussion over here - http://channel9.msdn.com/forums/Coffeehouse/20181-1st-Commercial-C-Game/
Comment posted by pavanireddy on Tuesday, September 16, 2008 6:44 AM
Hi,
How can i add Pagination to Datalist view
Comment posted by Suprotim Agarwal on Tuesday, September 16, 2008 9:24 AM
pavanireddy: Check this article of mine to see how to add sorting and paging in a listview

http://www.dotnetcurry.com/ShowArticle.aspx?ID=98
Comment posted by ramyasekar on Tuesday, October 7, 2008 2:04 AM
Hi There,

Nice article. Is it possible to select multiple images in the Picture album? and also have a custom scroll bar that we can scroll through and select pages and pages of images by holding shift and control keys like we do in Windows form applications
Comment posted by ramyasekar on Tuesday, October 7, 2008 2:34 AM
Hi There,

Nice article. Is it possible to select multiple images in the Picture album? and also have a custom scroll bar that we can scroll through and select pages and pages of images by holding shift and control keys like we do in Windows form applications
Comment posted by ramyasekar on Tuesday, October 7, 2008 5:45 PM
Hi There,

Nice article. Is it possible to select multiple images in the Picture album? and also have a custom scroll bar that we can scroll through and select pages and pages of images by holding shift and control keys like we do in Windows form applications
Comment posted by sanjeevkunar on Wednesday, October 8, 2008 5:14 AM
i am sanjeev kumar
Comment posted by Bengt on Wednesday, January 28, 2009 6:03 PM
The article is very detailed and easy to follow. However for the last three days I have tried to make the Image display. All I get i sthe Alternate text and no image. I am getting desperate at this point. I copied the code exactly as indicated. Can somebody help????
Comment posted by Bengt on Wednesday, January 28, 2009 7:38 PM
I found my problem.
Make sure that the ShowImage.ashx module is in the same folder as your webpage or you have to include the path to it.
Comment posted by Patrick on Wednesday, March 4, 2009 9:34 PM
is it possible to attach a link on each picture?  actually what i want to do is to display the picture (e.g. products), and when end user click on each picture it popup a bigger picture, it would be nice if this can be achieve via lightbox or ajax.
Comment posted by Soshians on Tuesday, July 14, 2009 6:41 AM
its very usefull article.
thanks a million
Comment posted by MarkW on Monday, August 10, 2009 9:49 AM
If you keep hitting the line "Throw New ArgumentException("No parameter specified")"
Just make sure you have a "set as Start page" set.
I was going mad as sometimes it worked and other time not!
Comment posted by Suprotim Agarwal on Tuesday, August 11, 2009 1:18 AM
MarkW: Thanks for that tip!
Comment posted by Shwetamber Chourey on Saturday, September 12, 2009 5:29 AM
I can not add ListView in my asp.net page it gives error.
"Operation could not be completed . Invalid FORMATETC structure".

Can any one suggest me where i am doing mistake.
Comment posted by Suprotim Agarwal on Wednesday, September 16, 2009 3:51 AM
Shwetamber: Not very sure why you get this error. Check this thread for possible solutions http://forums.asp.net/t/1122343.aspx  or this one  http://codeforfuture.com/2009/02/04/solution-invalid-formatetc-structure/
Comment posted by Sobin on Wednesday, December 16, 2009 4:53 AM
In the httphandler file you are calling  ShowAlbumImage(int picid)function,where you open and close database connection.What if there are 1000 pics in the album? Won't this affect the performance of the site?
Please reply
Comment posted by sathesh on Saturday, December 19, 2009 6:35 AM
its very usefull thanks...
i really got the material what i wanted....
thanks a lot.....
for your help....
Comment posted by srinivasu on Tuesday, January 12, 2010 12:19 AM
your posting is really good but i need few more examples
Comment posted by sdsd on Friday, March 5, 2010 3:11 AM
sasa
Comment posted by ipomz on Sunday, April 25, 2010 3:59 AM
test
Comment posted by Francisco on Monday, June 14, 2010 6:21 PM
Muy bueno tu ejemplo me ayudo mucho gracias
Comment posted by fadi on Sunday, January 23, 2011 2:32 AM
plz give me the pwd
Comment posted by Carol on Monday, January 24, 2011 3:00 AM
All passwords have been removed, however try dotnetcurry123#
Comment posted by praveen on Friday, February 25, 2011 7:30 AM
Imagegridview.aspx:==


using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public partial class imagegridview : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("server=mallesh;database=ImageDB;uid=sa;pwd=iqm");
    
    protected void btnSubmitCustImage_Click(object sender, EventArgs e)
    {
        if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
        {

            byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength];
            HttpPostedFile Image = FileUpload1.PostedFile;
            Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);

            SqlCommand storeimage = new SqlCommand("INSERT INTO ImageGallery(Image_Content, Image_Type, Image_Size) values (@image, @imagetype, @imagesize)", con);
            storeimage.Parameters.Add("@image", SqlDbType.Image, myimage.Length).Value = myimage;
            storeimage.Parameters.Add("@imagetype", SqlDbType.VarChar, 100).Value = FileUpload1.PostedFile.ContentType;
            storeimage.Parameters.Add("@imagesize", SqlDbType.BigInt, 99999).Value = FileUpload1.PostedFile.ContentLength;

            con.Open();
            storeimage.ExecuteNonQuery();
            con.Close();
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.DataSource = FetchAllImagesInfo();
        GridView1.DataBind();
    }
    public DataTable FetchAllImagesInfo()
    {
        string sql = "Select * from ImageGallery";
        SqlDataAdapter da = new SqlDataAdapter(sql, con);
        DataTable dt = new DataTable();
        da.Fill(dt);
        return dt;
    }
    
    
}



Handler.ashx:==

using System.Linq;
using System.Web;
using System.Data.SqlClient;  //Add this namespace
using System.Configuration; // Add this namespace
using System.Data; //Add this namespace
using System.IO; //Add this namespace

public class Handler : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        SqlConnection con = new SqlConnection("server=mallesh;database=ImageDB;uid=sa;pwd=iqm");
        con.Open();
        string sql = "Select Image_Content, Image_Type from ImageGallery where Img_Id=@ImageId";
        SqlCommand cmd = new SqlCommand(sql, con);
        cmd.Parameters.Add("@ImageId", SqlDbType.Int).Value = context.Request.QueryString["id"];
        cmd.Prepare();
        SqlDataReader dr = cmd.ExecuteReader();
        dr.Read();
        context.Response.ContentType = dr["Image_Type"].ToString();
        context.Response.BinaryWrite((byte[])dr["Image_Content"]);
        dr.Close();
        con.Close();
    }

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

Comment posted by rain91 on Wednesday, March 16, 2011 3:20 AM
Just wanna ask..can ur like resize the image to become more bigger?like when u on click, it will be bigger,
Comment posted by Romeo on Saturday, June 11, 2011 2:03 AM
Its a useful article and thanks . However SqlServer 2008 is featured with a new type functionality with a Filestream varbinary(max)field for storing images and videos how do we handle these with a ListView in Visual Studio 2008 Sp1. Could you explain it. Thanks in Advance
Comment posted by Mathew Uy on Monday, August 15, 2011 10:06 AM
Superb work sir. your tutorial is great, May I ask how to show a NO_IMAGE default picture if a picture is not found, Thank you.
Comment posted by Jamie on Tuesday, August 30, 2011 9:02 AM
This just helped me figure out how to display my images from the database into a modalpopupextender that is inside of a listview! Thank you so much for posting this!!!!!!!!! My code is here in case anyone else runs into that problem: http://stackoverflow.com/questions/7164688/asp-net-listview-ajax-modalpopupextender/7244469#7244469
Comment posted by Wael on Tuesday, January 10, 2012 12:36 AM
thank you it's a great job .
I want to ask when I save the picture on the database , the picture is seved twice it take two record .
Comment posted by honey chawla on Monday, January 23, 2012 8:59 AM
your code is not working. actually it is giving error 'no parameter specified' at
'context.Response.ContentType = "image/jpeg'. please help it.
Comment posted by sagar on Wednesday, March 14, 2012 2:18 AM
THIS IS NOT WORKING ANYMORE....
Comment posted by sharath mankala on Saturday, March 17, 2012 1:35 AM
Thanks sir .This code is working
please i want crystal reports.if any application is their send to my mail sir
sharath1245.siddipet@gmail.com
Comment posted by touseef on Wednesday, May 30, 2012 2:12 AM
thx sir
Comment posted by meysam on Sunday, July 29, 2012 4:58 PM
Very Nice.thank you
Comment posted by liran on Wednesday, August 15, 2012 6:11 PM
not work :|
Comment posted by rodmar on Saturday, September 8, 2012 6:53 AM
registration key????
Comment posted by rodmar on Saturday, September 8, 2012 10:00 PM
y my pic show in web is System.Byte[]?????
Comment posted by rodmar on Sunday, September 9, 2012 2:30 AM
hello.. can u plss answer this plss.
i have a listview in form1.. and iwant to call the listview in the codebehind of form2.
ex. Listview1.databinding();
Comment posted by sathish r on Friday, July 12, 2013 7:14 AM
Super,Fine work
Comment posted by Mikey on Monday, June 30, 2014 7:54 AM
Great code Suprotim
Just in case anybody is getting
Conversion from string "ShowImage.ashx?id=" to type 'Double' is not valid.].  Took me ages to work out why.  

Change: ImageUrl='<%# "ShowImage.ashx?id=" + Eval("pic_id")%>'
to: ImageUrl='<%# "ShowImage.ashx?id=" & Eval("pic_id")%>'
Comment posted by he-man on Wednesday, September 3, 2014 8:52 AM
very good trick but image size it not equal and also not showing in sequence
(thank you)