Click here to Skip to main content
15,867,568 members
Articles / Web Development / XHTML
Article

Slide-Show User Control

Rate me:
Please Sign up or sign in to vote.
4.91/5 (49 votes)
23 Jun 2008CPOL7 min read 196.2K   4.3K   116   52
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:

ASP.NET
<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:

C#
SlideShow1.ImageDataSource = GetImageItems();

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

C#
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:

ASP.NET
< ... EnableImageClick="true" ... >

Then, create an event handler for the Click event:

C#
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:

ASP.NET
< ... OnClick="SlideShow1_Click" ... > 

I’ll discuss about the SlideShowImageEventArgs class later.

User Control HTML

The HTML of this UserControl is very simple.

ASP.NET
<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.

C#
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:

C#
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.

C#
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:

C#
//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:

HTML
<head runat="server">

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

C#
//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:

C#
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:

C#
public event SlideShowClick Click;

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

C#
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:

C#
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:

C#
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:

ASP.NET
<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:

C#
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:

C#
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)


Written By
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

 
GeneralMy vote of 4 Pin
Shinigamae7-Oct-10 2:40
Shinigamae7-Oct-10 2:40 

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.