Sunday, April 3, 2011

Slide-Show User Control in



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.
  • 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();
   return JS.ToString();

private string GetCSS ()
   StringBuilder CSS= new StringBuilder();
   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
   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:

No comments:

Popular Posts