home » articles » Slide-Show User Control

Slide-Show User Control

change text size: A A A

11/26/2009 by samir.nigam

Download demo application - 39.3 KB

 pre

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:

pre2

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:

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:

ee

 

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.

 

This article has been re-published from - Original Article

To rate this article please register or login

Author

samir.nigam samir.nigam (Member since:10/22/2009)

Comments (no comments yet)

Post a comment

Comment (No HTML)  

Type the characters:
 *
 
   

Related articles

Join CodeAsp.Net for FREE Today!

It's fast, easy and free! Submit articles, get your own blog, ask questions & give answers in the forums, and become a better developer, faster.

enter your email address:

Latest Articles RSS Feed

Latest Articles

  • Hi Friends, Many times we came cross the requirement when we need to access the dropdownlist's selectedindexchanged event inside the gridview, like in a shopping cart changing the item's quantity or binding the other dropdown based on the first dropdown.
  • This is the approach that I have adopted to develop Expandable / Collapsible Panel Control through JavaScript. Please report bugs, errors and suggestions to improve this control.
  • This is my approach to develop custom JavaScript ListBox control. Although it is only a subset of existing HTML ListBox element, it is more user friendly than the existing one. It can be further customized for different requirements. Please let me know about bugs and/or errors & give suggestions to improve this ListBox control.
  • I have tried my best to make this user control code error free. I will most welcome suggestions for further improvement in this user control. I have tested this user control on various browsers and it works fine.
  • 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.
  • As we all knows that Repeater and DataList does not have auto paging support technique like Gridview or Datagrid, but we can achieve this through PagedDataSource. By using PagedDataSource we can implement paging in Repeater or DataList. Now in our mind there is question arise what is PagedDataSource. PagedDataSource is a class which encapsulates
  • So this is my approach. I was working for a long time to create C# like event handlers for JavaScript classes and finally, I’ve done it. Please let me know of any bugs and suggestions to improve this context menu control.
  • So this is my solution. If you have some other ideas about this functionality, please share them with me.
  • I have tried my best to make this code error free. Suggestions and criticism for further improvements of this code are most welcome.
  • So this is the approach that I've adopted to solve the Hover Delay problem. Although originally I developed Hover Delay to deactivate the click event for 1 second on a GridView row, later I also used Hover Delay to deactivate Drag n Drop of GridView rows. Kindly let me know if any one has some other better or different solution.
  • In this article I will explain how to import data from EXCEL to SQL in ASP.NET . In many situations we have data in the form of excel sheet but we have the requirement to have that data in SQL SERVER DB. I have explained importing data both from Excel 97-2003 as well as Excel 2007 format.
  • The source code shows how to use Regular Expressions in C#. The code Functions written for Validation Alphabet, AlphaNumeric, Integer, Postive Integer, Floating point numbers. You just cut copy these functions and use in any program.
  • That’s all about this technique. Just download the sample application and happy CSS! I have tested this application on various browsers and it worked fine.
  • This script is cross-browser compatible and fast as it iterates elements of a specific tag inside a target element [GridView] rather than iterating in a whole form. It searches the elements of a specific type in a particular column of the target element [GridView].
  • This Article is used to insert a numeric value on the sever control(text box) This is a java script code for the the client side validation. On Page Load Event You can change the events in txtNoOfQuestion.Attributes.Add("onkeypress", "return numericOnly(this);"); like onfocus events like other according to needs.
  • I have toggled visibility of all TD elements of a GridView column in order to create an illusion of smooth dynamic effect with the help of setTimeout method through recursion. Different browsers have different effects of Expanding / Collapsing GridView Columns. In Internet Explorer 7/8, Safari, Google Chrome and Opera, it seems that columns are Exp
  • In this article, I've used the setTimeout method in order to achieve a smooth expand/collapse functionality.
  • Introduction I am going to present here a functionality that selects / deselects all checkboxes of a particular column inside a GridView control, provided the header checkbox of that column is checked or unchecked using JavaScript. This functionality also has a feature that when all checkboxes of a particular column inside the GridView are check
  • This article describes how to toggle the states of all CheckBoxes inside a particular DataGridView column.
  • This article describes how to apply client-side mouse over & mouse out effects on the GridView’s rows.