Click here to Skip to main content
Click here to Skip to main content

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.

Preview.gif

Introduction

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.

Background

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:

Slide_Show.png

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.
  • 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;
      oImageItems.Add(oImageItem);
   }

   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:Label>
   </asp:Panel>
   <asp:Panel ID="pnlBase" runat="server">
      <table id="tblBase" border="0" cellpadding="0" cellspacing="0" 
             runat="server" style="position:absolute; left: 0px;">
         <tr>
            <td>
               <asp:DataList ID="dataList" runat="server" GridLines="Vertical" 
                    RepeatDirection="Horizontal" ShowHeader="False" 
                    CellPadding="0" OnItemCreated="dataList_ItemCreated"
                    ShowFooter="False">
                  <ItemTemplate>
                     <asp:ImageButton ID="imgSlideShow" alt="" ImageUrl='<%# Eval("URL") %>' 
                                      ToolTip='<%# Eval("ToolTip") %>' runat="server" />
                  </ItemTemplate>
                  <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
               </asp:DataList>
            </td>
         </tr>
      </table>
    </asp:Panel>
    <asp:Panel ID="pnlNavigation" runat="server" BackColor="#E0E0E0">
       <asp:HyperLink ID="aLeft" runat="server"></asp:HyperLink>
       <asp:HyperLink ID="aRight" runat="server"></asp:HyperLink>
    </asp:Panel>
</asp:Panel> 

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");
 
   ...

   JS.Append("</script>");
   return JS.ToString();
}

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

   ...

   CSS.Append("</style>");
   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);
else
   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:

error.png

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.

Conclusion

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:

Browsers.png

License

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

About the Author

Samir NIGAM
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,.

Awards:


Comments and Discussions

 
Questioni want this images to be of big size and text below Pinmemberdeveloperit15-Apr-12 0:35 
Questionhow to add user control? Pinmemberjayasathya23-Feb-12 1:03 
AnswerRe: how to add user control? Pinmemberjayasathya23-Feb-12 1:04 
GeneralRe: how to add user control? PinmemberSamir NIGAM23-Feb-12 3:09 
GeneralMy vote of 4 Pinmemberkhinlaiphyoaung2-Feb-12 20:00 
GeneralMy vote of 4 PinmemberShinigamae7-Oct-10 2:40 
GeneralNeed Vertical slideshow with top and bottom buttons PinmemberURSrafI12-Sep-09 19:02 
GeneralQuestion/Suggestion Pinmembertvos23-Apr-09 6:42 
GeneralRe: Question/Suggestion PinmemberSamir NIGAM23-Feb-12 3:14 
GeneralA question PinmemberKennetho14-Jan-09 10:32 
GeneralRe: A question PinmvpSameer NIGAM15-Jan-09 1:16 
GeneralWonderful control PinmemberSharpkiller_bg00710-Dec-08 19:08 
You are really a genius! Thank you for your good control, it saves me much time!
 
I love this site!

GeneralRe: Wonderful control PinmemberSameer NIGAM10-Dec-08 23:10 
Generalscrolling speed Pinmemberdilson11-Nov-08 21:43 
Generalscroll control that i've been looking for Pinmemberdilson11-Nov-08 21:32 
GeneralRe: scroll control that i've been looking for PinmemberSamir NIGAM23-Feb-12 3:15 
Questionhow can I start pic move left or right on page_load? PinmemberJLKEngine0081-Sep-08 17:01 
QuestionIt is possible? PinmemberBorginer4-Jul-08 3:24 
AnswerRe: It is possible? PinmemberSAMir Nigam4-Jul-08 18:49 
GeneralControl doesn't seem to work on Multiview Control Form Pinmemberroyal_hale29-Jun-08 15:20 
GeneralCool Stuff PinmemberRajib Ahmed17-Jun-08 5:18 
GeneralRe: Cool Stuff PinmemberSAMir Nigam18-Jun-08 18:04 
Generalvery good work PinmemberViral Upadhyay16-Jun-08 20:20 
GeneralRe: very good work Pinmember SAMir Nigam 16-Jun-08 20:43 
Generalusing Datasource or Dataset to reterive images PinmemberAdnanSabir15-Jun-08 22:33 
GeneralRe: using Datasource or Dataset to reterive images Pinmember SAMir Nigam 16-Jun-08 17:42 
General[Message Removed] PinmemberMojtaba Vali8-Jun-08 17:52 
GeneralRe: comments for images Pinmember SAMir Nigam 8-Jun-08 19:20 
QuestionHow do i handle image click event PinmemberMember 215831829-May-08 2:11 
AnswerRe: How do i handle image click event Pinmember SAMir Nigam 29-May-08 3:21 
GeneralGood Work PinmemberAbhijit Jana28-May-08 21:54 
GeneralRe: Good Work Pinmember SAMir Nigam 28-May-08 23:15 
GeneralSuggestion ( Programatically Adding Javascript and CSS code ) PinmemberRanjan.D28-May-08 18:01 
GeneralRe: Suggestion ( Programatically Adding Javascript and CSS code ) Pinmember SAMir Nigam 28-May-08 18:53 
GeneralRe: Suggestion ( Programatically Adding Javascript and CSS code ) Pinmembersnancy19-May-09 20:40 
GeneralRe: Suggestion ( Programatically Adding Javascript and CSS code ) PinmvpSamir NIGAM19-May-09 21:37 
GeneralRe: Suggestion ( Programatically Adding Javascript and CSS code ) Pinmembersnancy19-May-09 22:59 
GeneralRe: Suggestion ( Programatically Adding Javascript and CSS code ) Pinmembersnancy19-May-09 23:56 
GeneralRe: Suggestion ( Programatically Adding Javascript and CSS code ) PinmvpSamir NIGAM20-May-09 0:09 
GeneralRe: Suggestion ( Programatically Adding Javascript and CSS code ) Pinmembersnancy2-Jun-09 23:47 
GeneralRe: Suggestion ( Programatically Adding Javascript and CSS code ) PinmemberSAMir Nigam27-Jun-08 20:30 
GeneralSuggestion PinmemberPaul Selormey28-May-08 15:08 
GeneralRe: Suggestion Pinmember SAMir Nigam 28-May-08 18:49 
GeneralRe: Suggestion PinmemberPaul Selormey28-May-08 19:05 
GeneralRe: Suggestion Pinmember SAMir Nigam 28-May-08 20:12 
GeneralGreat PinmemberMCSDvikasmisra28-May-08 5:47 
GeneralRe: Great Pinmember SAMir Nigam 28-May-08 18:46 
GeneralOnce Again Great Work Sir PinmemberSandeep Shekhar28-May-08 0:33 
GeneralRe: Once Again Great Work Sir Pinmember SAMir Nigam 28-May-08 18:32 
GeneralSome suggestions PinmemberN a v a n e e t h27-May-08 20:23 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140709.1 | Last Updated 23 Jun 2008
Article Copyright 2008 by Samir NIGAM
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid