Click here to Skip to main content
13,832,353 members
Click here to Skip to main content
Add your own
alternative version


116 bookmarked
Posted 27 May 2008
Licenced CPOL

Slide-Show User Control

, 23 Jun 2008
Rate this:
Please Sign up or sign in to vote.
This article describes how to create a slide-show user control with the help of the DataList control.



In this article, I’m going to present an implementation of an ASP.NET slide show user control. It is an HTML table based slide show. It is a very simple user control and can easily be modified depending upon your needs.


A few months ago, I was searching the Internet for a JavaScript slide show that could easily be applied to a DataList control. I found some good JavaScript slide show samples, but all of them were div based and not HTML table based. Also, the JavaScript was very complicated and very difficult to grasp. So, I decided to develop my own HTML table based JavaScript slide show. Later, I converted it to a User Control so that it could easily be modified and reused depending upon future needs.

About the User Control

At runtime, the slide show user control has the following appearance:


The upper part contains the title of the slide show while the lower part contains the left and right arrows (hyperlinks). The middle part consists of the necessary images for the slide show. When we put the mouse pointer over the left arrow, the images start to move from right to left, and when we put the mouse pointer over the right arrow, the images start to move from left to right. When we remove the mouse pointer from the left or right arrow, the slide show doesn’t stop immediately. The movement of the current image first completes, and then the slide show stops. The speed of the slide show differs from browser to browser in this user control.

Properties of the User Control

The slide show user control has the following public properties:

  • NoOfVisibleImages: The number of visible images.
  • ImageHeight: The height of the image.
  • ImageWidth: The width of the image.
  • ImageDataSource: The image item collection.
  • RightImage: Path of the right arrow image.
  • LeftArrowToolTip: Tool tip for the left arrow image.
  • RightArrowToolTip: Tool tip for the right arrow image.
  • Title: Title for the user control.
  • ArrowAlign: Horizontal alignment for the navigation arrows.
  • TitleAlign: Horizontal alignment for the user control title.
  • </strong />SlideShowSpeed: Speed of the slide show in milliseconds. The default value for it is 10 milliseconds.
  • EnableImageClick: Specifies whether to enable the Click event or not. The default value for it is false.

Events of the User Control

The slide show user control has only one server-side event:

  • Click: Fires when an image of the SlideShow is clicked.

Using the User Control

Drag and drop the user control into an ASPX page and set the values for its properties. The HTML code for this user control looks like:

<uc1:SlideShow ID="SlideShow1" runat="server" NoOfVisibleImages="4" 

     ImageHeight="71" ImageWidth="95" LeftImage="~/ArrowImages/back[1].gif" 

     RightImage="~/ArrowImages/next[1].gif" Title="Image Slide Show"

     ArrowAlign="Left" TitleAlign="Left" />

Now, bind the slide show user control to an image data source of type ImageItems in the Page_Load event:

SlideShow1.ImageDataSource = GetImageItems();

where the method GetImageItems returns an ImageItems collection. The code for the method GetImageItems is given below:

private ImageItems GetImageItems()
   ImageItems oImageItems = new ImageItems();
   ImageItem oImageItem = null;

   FileInfo[] Images = new DirectoryInfo(Server.MapPath("Images")).GetFiles("*.*");

   foreach (FileInfo Image in Images)
      oImageItem = new ImageItem();
      oImageItem.URL = string.Format("~/Images/{0}", Image.Name);
      oImageItem.ToolTip = Image.Name;

   return oImageItems;

You can also handle the Click event of the slide show user control. For this, first you have to enable the Click event as:

< ... EnableImageClick="true" ... >

Then, create an event handler for the Click event:

protected void SlideShow1_Click(object sender, SlideShowImageEventArgs e)

Next, wire up the event handler in the control tag by adding the prefix On in front of the event name:

< ... OnClick="SlideShow1_Click" ... > 

I’ll discuss about the SlideShowImageEventArgs class later.

User Control HTML

The HTML of this UserControl is very simple.

<asp:Panel ID="pnlParent" runat="server">
   <asp:Panel ID="pnlTitle" runat="server" HorizontalAlign="Left">      
      <asp:Label ID="lblTitle" runat="server" Text="Slide Show" 

           Font-Bold="True" Font-Names="Garamond" ForeColor="#404040">
   <asp:Panel ID="pnlBase" runat="server">
      <table id="tblBase" border="0" cellpadding="0" cellspacing="0" 

             runat="server" style="position:absolute; left: 0px;">
               <asp:DataList ID="dataList" runat="server" GridLines="Vertical" 

                    RepeatDirection="Horizontal" ShowHeader="False" 

                    CellPadding="0" OnItemCreated="dataList_ItemCreated"

                     <asp:ImageButton ID="imgSlideShow" alt="" ImageUrl='<%# Eval("URL") %>' 

                                      ToolTip='<%# Eval("ToolTip") %>' runat="server" />
                  <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
    <asp:Panel ID="pnlNavigation" runat="server" BackColor="#E0E0E0">
       <asp:HyperLink ID="aLeft" runat="server"></asp:HyperLink>
       <asp:HyperLink ID="aRight" runat="server"></asp:HyperLink>

There are three Panels in this UserControl inside a parent Panel [ID="pnlParent"]. The first Panel [ID="pnlTitle"] has been used to display the title of the user control. It contains a Label control for this purpose.

The second Panel [ID="pnlBase"] has been used to display the images of the slide show. It contains an HTML table [id="tblBase"] with position equal to absolute [style="position: absolute;”]. Here, position equal to absolute has been used so that the position of the HTML table within the container Panel [ID="pnlBase"] can be changed at runtime using JavaScript to create a moving effect. This HTML table holds a DataList server control with RepeatDirection="Horizontal". Actually, this DataList [ID="dataList"] has been used here in order to bind images to the user control. An ImageButton server control [ID="imgSlideShow"] has been put inside the ItemTemplate for this purpose. Data-binding expressions have been used to set the ImageUrl and ToolTip properties of the Image server control.

The third Panel [ID="pnlNavigation"] has been taken to display the left and right arrows. These left and right arrows are responsible for the motion of the images from right to left or from left to right. Two HyperLink controls [ID="aLeft" and ID="aRight"] have been put inside this Panel for this purpose.

User Control Code

The SlideShow class is derived from the System.Web.UI.UserControl class.

public partial class SlideShow : System.Web.UI.UserControl

The Height and Width of each image has been set in the ItemCreated event of the DataList:

if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
   ImageButton imgSlideShow = (ImageButton)e.Item.FindControl("imgSlideShow");
   imgSlideShow.Height = Unit.Pixel(_ImageHeight);
   imgSlideShow.Width = Unit.Pixel(_ImageWidth);

There are two private methods: GetCSS and GetJS in the SlideShow class that emit the necessary JavaScript and CSS for this UserControl at client side.

private string GetJS()
   StringBuilder JS = new StringBuilder();
   JS.Append("<script type=\"text/javascript\">\n");

   return JS.ToString();

private string GetCSS ()
   StringBuilder CSS= new StringBuilder();
   CSS.Append("<style type=\"text/css\">\n");


   return CSS.ToString();

The CSS has been attached to the page’s header section in the Page_Load event of the UserControl as:

//Adding a stylesheet to the page header
((HtmlHead)this.Page.Header).Controls.Add(new LiteralControl(GetCSS()));

Note that in order to attach the necessary CSS through code, the page’s header section should be marked as runat=server as:

<head runat="server">

The JavaScript has been registered to the page in the Page_Load event of the User Control as:

//Register client side script.
this.Page.ClientScript.RegisterStartupScript(typeof(Page), "MyScript", GetJS());

Client side mouseover and mouseout events also have been attached to the left and right HyperLink controls in the Page_Load event of the User Control as:

aLeft.Attributes["onmouseover"] = "javascript:Start();MoveLeft();";
aLeft.Attributes["onmouseout"] = "javascript:Stop();StopMoveLeft();";
aRight.Attributes["onmouseover"] = "javascript:Start();MoveRight();";
aRight.Attributes["onmouseout"] = "javascript:Stop();StopMoveRight();";

The slide show user control has following definition for its Click event:

public event SlideShowClick Click;

The delegate that represents the Click event has the following signature:

public delegate void SlideShowClick(object sender, SlideShowImageEventArgs e); 

The Click event for this user control has been fired in the click event of the ImageButton as:

protected void imgSlideShow_Click(object sender, ImageClickEventArgs e)
   // Fire the event.
   if (Click != null)
      Click(this, new SlideShowImageEventArgs((ImageButton)sender, e.X, e.Y));

The Click event has been attached to each of the ImageButton control in the ItemCreated event of the DataList in the following manner:

if (_EnableImageClick)
   imgSlideShow.Click += new ImageClickEventHandler(imgSlideShow_Click);
   imgSlideShow.Attributes["onclick"] = "javascript:return false;";

Note that if EnableImageClick is false, then post back is been prevented through JavaScript. One more important thing: put the following line of the code in the system.web section of the web.config file if you want to handle the Click event of the slide show user control, i.e., if EnableImageClick is true:

<pages enableEventValidation="false"></pages>

If you don’t add this line of the code, then you will face the following error:


I’ve tried to handle it through code, but couldn’t. If any one has ideas about it, then please let me know.

SlideShowImageEventArgs is an event argument class for this user control and has some basic information about the Image to be clicked. The definition of this class is given below:

public class SlideShowImageEventArgs : EventArgs
    private ImageButton _ImageButton = null;
    private int _X = 0;
    private int _Y = 0;

    public int X
        get { return _X; }

    public int Y
        get { return _Y; }

    public string URL
        get { return _ImageButton.ImageUrl; }

    public string ToolTip
        get { return _ImageButton.ToolTip; }

    public SlideShowImageEventArgs(ImageButton O, int X, int Y)
        _ImageButton = O;
        _X = X;
        _Y = Y;

Images Source

The slide show user control has a public property, ImageDataSource. This is used to bind image items to the user control for the slide show. The ImageDataSource property accepts a collection of image items of type ImageItems as the image data source. ImageItems is a generic collection class inherited from the List<ImageItem> class. The definitions for the ImageItems and ImageItem classes are given below:

public class ImageItems : List<ImageItem>
   public ImageItems() { }

public class ImageItem
   private string _ToolTip = string.Empty;
   public string ToolTip
      get { return _ToolTip; }
      set { _ToolTip = value; }

   private string _URL = string.Empty;
   public string URL
      get { return _URL; }
      set { _URL = value; }

   // Default constructor.
   public ImageItem() { }

   public ImageItem(string ToolTip, string URL)
      this._ToolTip = ToolTip;
      this._URL = URL;

JavaScript Methods

There are six JavaScript methods that are responsible for performing the slide show on the client side, namely: Start, Stop, MoveLeft, StopMoveLeft, MoveRight, and StopMoveRight. As soon as we put the mouse pointer over the left or right HyperLnk, the onmouseover event gets fired. The Start method is first invoked and it sets a global flag equal to false [IsPaused = false;] indicating that the slide show is about to start. After that, the MoveLeft or MoveRight method is invoked. These methods are responsible for moving the images from right to left or left to right for the slide show. When we remove the mouse pointer from the left or right HyperLnk, the onmouseout event is fired. The Stop method is first invoked and it sets a global flag equal to true [IsPaused = true;] indicating that the slide show is about to stop. After that, the StopMoveLeft or StopMoveRight method is invoked. These methods don’t immediately stop the slide show. Rather, these methods first complete the movements of the current image from right to left or left to right, then stops the slide show.


So, this is my approach to implement an ASP.NET slide show using the DataList. I have tried my best to keep it bug free. I will most welcome suggestions and criticism for further improvements of this user control. I have tested this user control on various browsers and it works fine. A list of supported browsers along with versions is given below:



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Technical Lead Infogain India Pvt Ltd
India India

Samir NIGAM is a Microsoft Certified Professional. He is an insightful IT professional with results-driven comprehensive technical skill having rich, hands-on work experience n web-based applications using ASP.NET, C#, AJAX, Web Service, WCF, jQuery, Microsoft Enterprise Library , LINQ, MS Entity Framework, nHibernate, MS SQL Server & SSRS.

He has earned his master degree (MCA) from U.P. Technical University, Lucknow, INDIA, his post graduate dipoma (PGDCA ) from Institute of Engineering and Rural Technology, Allahabad, INDIA and his bachelor degree (BSc - Mathematics) from University of Allahabad, Allahabad, INDIA.

He has good knowledge of Object Oriented Programming, n-Tier Architecture, SOLID Principle, and Algorithm Analysis & Design as well as good command over cross-browser client side programming using JavaScript & jQuery,.


You may also be interested in...


Comments and Discussions

Questioni want this images to be of big size and text below Pin
developerit15-Apr-12 1:35
memberdeveloperit15-Apr-12 1:35 
Questionhow to add user control? Pin
jayasathya23-Feb-12 2:03
memberjayasathya23-Feb-12 2:03 
AnswerRe: how to add user control? Pin
jayasathya23-Feb-12 2:04
memberjayasathya23-Feb-12 2:04 
GeneralRe: how to add user control? Pin
Samir NIGAM23-Feb-12 4:09
memberSamir NIGAM23-Feb-12 4:09 
GeneralMy vote of 4 Pin
khinlaiphyoaung2-Feb-12 21:00
memberkhinlaiphyoaung2-Feb-12 21:00 
GeneralMy vote of 4 Pin
Shinigamae7-Oct-10 3:40
memberShinigamae7-Oct-10 3:40 
GeneralNeed Vertical slideshow with top and bottom buttons Pin
URSrafI12-Sep-09 20:02
memberURSrafI12-Sep-09 20:02 
GeneralQuestion/Suggestion Pin
tvos23-Apr-09 7:42
membertvos23-Apr-09 7:42 
GeneralRe: Question/Suggestion Pin
Samir NIGAM23-Feb-12 4:14
memberSamir NIGAM23-Feb-12 4:14 
GeneralA question Pin
Kennetho14-Jan-09 11:32
memberKennetho14-Jan-09 11:32 
GeneralRe: A question Pin
Samir NIGAM15-Jan-09 2:16
memberSamir NIGAM15-Jan-09 2:16 
GeneralWonderful control Pin
Sharpkiller_bg00710-Dec-08 20:08
memberSharpkiller_bg00710-Dec-08 20:08 
GeneralRe: Wonderful control Pin
Samir NIGAM11-Dec-08 0:10
memberSamir NIGAM11-Dec-08 0:10 
Generalscrolling speed Pin
dilson11-Nov-08 22:43
memberdilson11-Nov-08 22:43 
Generalscroll control that i've been looking for Pin
dilson11-Nov-08 22:32
memberdilson11-Nov-08 22:32 
GeneralRe: scroll control that i've been looking for Pin
Samir NIGAM23-Feb-12 4:15
memberSamir NIGAM23-Feb-12 4:15 
Questionhow can I start pic move left or right on page_load? Pin
JLKEngine0081-Sep-08 18:01
memberJLKEngine0081-Sep-08 18:01 
QuestionIt is possible? Pin
Borginer4-Jul-08 4:24
memberBorginer4-Jul-08 4:24 
AnswerRe: It is possible? Pin
Samir NIGAM4-Jul-08 19:49
memberSamir NIGAM4-Jul-08 19:49 
GeneralControl doesn't seem to work on Multiview Control Form Pin
royal_hale29-Jun-08 16:20
memberroyal_hale29-Jun-08 16:20 
GeneralCool Stuff Pin
Rajib Ahmed17-Jun-08 6:18
memberRajib Ahmed17-Jun-08 6:18 
GeneralRe: Cool Stuff Pin
Samir NIGAM18-Jun-08 19:04
memberSamir NIGAM18-Jun-08 19:04 
Generalvery good work Pin
Viral Upadhyay16-Jun-08 21:20
memberViral Upadhyay16-Jun-08 21:20 
GeneralRe: very good work Pin
Samir NIGAM16-Jun-08 21:43
memberSamir NIGAM16-Jun-08 21:43 
Generalusing Datasource or Dataset to reterive images Pin
AdnanSabir15-Jun-08 23:33
memberAdnanSabir15-Jun-08 23:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web04 | 2.8.190114.1 | Last Updated 23 Jun 2008
Article Copyright 2008 by Samir NIGAM
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid