Geeks With Blogs
Bunch's Blog One day I'll have a catchy subtitle, one day

This post goes over how to display images stored in a database using the SlideShowExtender control. The examples use VB.Net (what I have to use at the office) and assumes that you are storing your images in a database, have a way to retrieve the images from the database (e.g. stored procedure) and have AJAX (example is based on the AJAX controls in VS2008) setup in your ASP.Net project already. Also the example was based on retrieving images that are photos hence the names of some of the various functions, controls, etc.

The first piece is the SlideShowExtender, image control and the button controls on your aspx page. The example below does not use the Loop or PlayButtonID properties since I used it more as a picture gallery rather than cycling through images. Just add the Loop=’true’ property and another control for the play/stop button if you wanted to do that (an example here).

<asp:Image ID="imgPhoto" runat="server" Height="175px"  />
<br />
    <asp:Button ID="btnPrevPhoto" runat="server" Text="Prev" />
    <asp:Button ID="btnNextPhoto" runat="server" Text="Next" />
<cc1:SlideShowExtender ID="ssePhotos" runat="server" TargetControlID="imgPhoto" AutoPlay="false"
PreviousButtonID="btnPrevPhoto" NextButtonID="btnNextPhoto" SlideShowServicePath="Photos.asmx"
SlideShowServiceMethod="GetPhotos" ContextKey="123">

So now you have an image control to show the image, a button to cycle to the next image, a button to go back to the previous image and the SlideShowExtender itself. All that is pretty straightforward, the real guts of how it works lies in the web service (asmx file) and the web handler (ashx file). One very important property to note is the ContextKey. This is the value that you can pass to your function to retrieve your photos. In this example it is an ID for a group of photos and that ID is stored in the database. This would depend on how your table storing the images are setup but probably you have some sort of ID that goes along with a group of images (a site, an item, etc.). In reality that value would NOT be hard coded in but set in the code behind file.

The SlideShowServicePath property is set to Photos.asmx. This is a small web service that will add the images to a AjaxControlToolkit.Slide array. The SlideShowServiceMethod property contains the function in the web service that handles retrieving the images (with the help of the web handler). One key item, DO uncomment the <System.Web.Script.Services.ScriptService()> line. Otherwise a script (like the AJAX control) will not work. Here is the code for the web service:

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Data.SqlClient
Imports System.Data.Sql
Imports System.Data

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class SitePhotos
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function GetPhotos(ByVal contextKey As String) As AjaxControlToolkit.Slide()
        Dim photoReader As SqlDataReader
        Dim conn As SqlConnection = New SqlConnection
        Dim cmd As SqlCommand = New SqlCommand

        conn.ConnectionString = ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString
        cmd.CommandType = CommandType.StoredProcedure
        cmd.Connection = conn
        cmd.CommandText = "spGetThumbnailIDs"
        cmd.Parameters.Add("@ID", SqlDbType.Int)
        cmd.Parameters("@ID").Value = contextKey

        photoReader = cmd.ExecuteReader()

        Dim slides(24) As AjaxControlToolkit.Slide
        Dim i As Integer = 0
        While photoReader.Read
            slides(i) = New AjaxControlToolkit.Slide("Photo.ashx?TypeID=1&PhotoID=" & photoReader("ThumbnailID"), "test", "test")
            i += 1
        End While

        i -= 1
        ReDim Preserve slides(i)

        Return slides
    End Function
End Class

The first half of the GetPhotos function deals with making the database connection and executing the stored procedure (MSSQL). The variable slides is setup with 25 possible items so if you needed to display 50 items declare slides(49). The SqlDataReader reads in each image’s ThumbnailID and using the help of the ashx file (more on that later) adds the actual image data to slides. After the reading is complete the counter variable is set to one less than it is and slides is ReDimmed to eliminate any empty items that may exist. If this is not done then the SlideShowExtender will try and cycle through the empty items.

Before showing the web handler let me explain the various ids used in the GetPhotos function. The ID of the group of images needed is passed as the contextKey to the function. The spGetThumbnailIDs stored procedure then returns the ThumbnailIDs that are associated with ID into photoReader. The photoReader does not actually deal with the stored image file, the web handler retrieves that data and puts in the slides variable based on the ThumbnailID read from photoReader.

Now for the web handler file.

<%@ WebHandler Language="VB" Class="Photo" %>

Imports System
Imports System.Web
Imports System.Data

Public Class Photo : Implements IHttpHandler
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim sdsPhoto As SqlDataSource = New SqlDataSource
        sdsPhoto.ConnectionString = ConfigurationManager.ConnectionStrings("My_ConnectionString").ConnectionString
        sdsPhoto.SelectCommand = "spGetPhotos"
        sdsPhoto.SelectCommandType = SqlDataSourceCommandType.StoredProcedure
        sdsPhoto.SelectParameters.Add("ID", context.Request.QueryString("PhotoID"))
        Dim dv As DataView = sdsPhoto.Select(DataSourceSelectArguments.Empty)
        Dim dr As DataRow
            dr = dv.Table.Rows(0)
            context.Response.Write("No Image Found")
            Exit Sub
        End Try
        Dim arrImage() As Byte = CType(dr("Image"), Byte())
    End Sub
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
            Return False
        End Get
    End Property

End Class

This file takes the ThumbnailID and uses it in the spGetPhotos stored procedure to retrieve the actual image data. Again the first half of the sub is setting up the database connection. The image is then stored in the arrImage byte.

One final note the web handler can also be used to display images without the SlideShowExtender. You can use the ashx file in controls like the ImageButton and use the path in the ImageUrl.

Technorati Tags: ,,
Posted on Friday, September 17, 2010 9:51 AM | Back to top

Comments on this post: Using the AJAX SlideShowExtender with database images

# re: Using the AJAX SlideShowExtender with database images
Requesting Gravatar...

I tried to use this method in my website. But it is giving these messages/errors and not diplaying the pictures.

error 1:

Microsoft JScript runtime error: AjaxControlToolkit requires ASP.NET Ajax 4.0 scripts. Ensure the correct version of the scripts are referenced. If you are using an ASP.NET ScriptManager, switch to the ToolkitScriptManager in AjaxControlToolkit.dll.

I am already using a toolkitscriptmanager.
error 2:

Microsoft JScript runtime error: Object doesn't support this property or method

any help would be greatly appreciated.

Left by triveni on Sep 21, 2010 3:29 PM

# re: Using the AJAX SlideShowExtender with database images
Requesting Gravatar...
Can u please send me these files in a zip folder.
So I can try to edit them please
Left by Gracien on Dec 31, 2011 3:50 AM

# re: Using the AJAX SlideShowExtender with database images
Requesting Gravatar...
i want above code need in csharp
Left by ghanuvank on Jan 29, 2012 3:00 PM

# re: Using the AJAX SlideShowExtender with database images
Requesting Gravatar...
can you give me file in zip?
Left by thika on Jun 10, 2012 8:16 AM

# re: Using the AJAX SlideShowExtender with database images
Requesting Gravatar...
I want above code need in csharp.
Can you give me zip file please?
Left by Mahesh on Sep 17, 2012 1:07 AM

# re: Using the AJAX SlideShowExtender with database images
Requesting Gravatar...
Hi Bunch,

I tried to pass this code to csharp, but de handler doesn´t run from de webservice. ¿Do you have this code in csharp that youl could send me?

Left by Juan Pablo Echeverri V. on Oct 14, 2012 5:16 PM

# Demo File in Image Slider in with database Connectivity
Requesting Gravatar...
Please forward this Immidiatly...
Left by Sandip Patil on Jan 12, 2013 2:37 AM

Your comment:
 (will show your gravatar)

Copyright © Bunch | Powered by: