Click here to Skip to main content
15,885,773 members
Articles / Web Development / ASP.NET
Article

A Custom Image Button Control with Mouse-Over Effects and Client Side Action

Rate me:
Please Sign up or sign in to vote.
3.77/5 (7 votes)
14 Aug 20067 min read 87.5K   1K   27   8
This article describes an easy approach to the construction of a custom ASP.NET 2.0 image button control that contains both a mouse-over effect and calls a JavaScript function when clicked.

Image 1

Introduction

This article describes an easy approach to the construction of a custom ASP.NET 2.0 image button control that contains both a mouse-over effect and calls a JavaScript function when clicked. Whilst the article is pretty simple and the code fairly trivial, the concepts illustrated by means of this example are relatively important and are key to integrating client side functionality into an ASP.NET 2.0 project.

The two important items to pull from this article are:

  1. that you can add attributes to a custom control, and
  2. that you can embed and evoke JavaScript functions from a custom control.

One possible use for this control may be to drop several of them into a Panel and use the Panel and collection as a toolbar. Naturally, the control would work just fine as a standalone control as well.

Getting Started

In order to get started, open up the Visual Studio 2005 IDE and start a new project. From the New Project dialog (Figure 1), under Project Types, select the “Windows” node from beneath “Visual Basic”, then select the “Web Control Library” template in the right hand pane. Key in a name for the project and then click “OK”.

Once the project has opened; right click on the solution and click on the “Add” menu option, and then select “New Item”. When the “Add New Item” dialog appears (Figure 2), select the “Web Custom Control” template. After selecting the template, key “MOEbutton.vb” into the name field, and then click “Add” to close the dialog. You may now delete the default web control that was created when the project was originally initialized from the template.

At this point, we should have an open web control library project, with a single web control named “MOEbutton.vb” in that project. One last step prior to writing the code for this project will be to add in one needed reference. To add this reference, double click on the “My Project” icon in the Solution Explorer to open “My Project”. From here, select the “References” tab, and then click the “Add” button. When the “Add Reference” dialog opens, select the .NET tab, and search down the list until you find the “System.Design” reference. Select this library, and click on the “OK” button.

Image 2

Figure 1: Visual Studio 2005 New Project Dialog

Image 3

Figure 2: Add New Item Dialog

Navigate back to the “MOEbutton.vb” file and, at the top of the file, add in the Imports statements highlighted below:

VB
Imports System
Imports System.ComponentModel
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.Design

<DefaultProperty("Text"), _
 ToolboxData("<{0}:MOEbutton runat=server></{0}:MOEbutton>")>_
Public Class MOEbutton
    Inherits WebControl

We are now ready to add the code necessary to make this control functional. First off, we need to create a few private member variables; these variables will be used to contain the paths to the image files used to display the normal and mouse-over effects on the control, to contain a string with the JavaScript to be applied to the button’s OnClick event, and a declaration of an HTML input image control that will be used as the basis for this customization (note that the HtmlInputImage button is declared with events). To accomplish these steps, create a “Declarations” region, and key in the following variable declarations:

VB
#Region "Declarations"
     'create private member variables used by this control

    Private mMouseOverImage As String
    Private mMouseOutImage As String
    Private mJavaScriptCall As String

    Private WithEvents imgButton As HtmlControls.HtmlInputImage

#End Region

The next thing to do is to set up a couple of simple initialization settings; we can do that in the public Sub New declaration and in the MOEbutton's Load event (add a "Methods" region and key in the following):

VB
#Region "Methods"
     Public Sub New()
        'initialize new controls with a default height and width
        Me.Width = 24
        Me.Height = 24

    End Sub


    Private Sub MOEbutton_Load(ByVal sender As Object, _
            ByVal e As System.EventArgs) Handles Me.Load
        EnsureChildControls()
    End Sub

#End Region

Once the variables are declared, we will need to provide public properties to expose the control's properties to the control user; in order to accomplish these steps, create a “Properties” region and key in the following code:

VB
#Region "Properties"
     ' create public properties for member variables

    <Category("Button Images")>_
    <Browsable(True)>_
    <Description("Set path to mouseover image file.")>_
    <Editor(GetType(System.Web.UI.Design.UrlEditor),
    GetType(System.Drawing.Design.UITypeEditor))>_
    Public Property MouseOverImage() As String
        Get
            Return mMouseOverImage
        End Get
        Set(ByVal value As String)
            mMouseOverImage = value
        End Set
    End Property


    <Category("Button Images")>_
    <Browsable(True)>_
    <Description("Set path to mouseout image file.")>_
    <Editor(GetType(System.Web.UI.Design.UrlEditor),
    GetType(System.Drawing.Design.UITypeEditor))>_
    Public Property MouseOutImage() As String
        Get
            Return mMouseOutImage
        End Get
        Set(ByVal value As String)
            mMouseOutImage = value
        End Set
    End Property


    <Category("JavaScript")>_
    <Browsable(True)>_
    <Description("Set javascript string for onclick event.")>_
    Public Property JavaScriptCall() As String
        Get
            Return mJavaScriptCall
        End Get
        Set(ByVal value As String)
            mJavaScriptCall = value
        End Set
    End Property

#End Region

Note that, in the attributes section above each file path related property declaration, the code specifies an editor, and further that the editor specified is defined as the URL Editor. Adding this attribute to the control specifies to the IDE how the property is to be edited; in this instance, when the control user sets the image file path properties for the control, the property grid will display a button with an ellipsis in it at the right hand side of the text box. If the user clicks on the button, the IDE will open the URL editor, and will permit the user to use that editor to navigate to the image file and set the image file path property through that editor’s dialog.

Properties set in this manner will be persisted within the control user’s project. Note that the URL editor will prefix the selected path with a tilde and a slash, neither of which is useful in this context. You may wish to parse the string returned from the URL editor (in the Set region of each image file path property) to strip off the first two characters before storing the selection). This path will be passed to the “OnMouseOver” and “OnMouseOut” calls, and if the tilde is present, the file will not be located.

VB
<Editor(GetType(System.Web.UI.Design.UrlEditor), _ 
  GetType(System.Drawing.Design.UITypeEditor))>_

At this point, the only thing left to do is to define how the control will be rendered. To complete this step, create a “Rendering” region and, within this region, override the CreateChildControls() method with the following code:

VB
#Region "Rendering"
     Protected Overrides Sub CreateChildControls()

        imgButton = New HtmlControls.HtmlInputImage()
        imgButton.Src = MouseOutImage.ToString()
        imgButton.Attributes.Add("onmouseover", "this.src='" & _
                  MouseOverImage.ToString() & "';")
        imgButton.Attributes.Add("onmouseout", "this.src='" & _
                  MouseOutImage.ToString() & "';")
        imgButton.Attributes.Add("onclick", JavaScriptCall.ToString())
        Controls.Add(imgButton)

    End Sub

#End Region

Within this code, there are a few things worth looking at; first, you will note that a new instance of an HtmlInputImage control is created. After this object is created, its src property is set to point to the path stored for the MouseOutImage property. Next, the OnMouseOver and OnMouseOut attributes are added to the imgButton control, and their image source files are set to be updated whenever the OnMouseOver or OnMouseOut events are fired. Next up, the “OnClick” attribute is added to the control, and the JavaScript string contained in the JavaScriptCall property is assigned to the “OnClick” event. While this example is basic and uses only a string containing a simple JavaScript call, the function could also name a JavaScript function contained in an external registered JavaScript file, or could contain a complex function defined within this class and subsequently registered for later use.

The control is now complete. Prior to testing the control, rebuild the project. Once that has been completed and any errors encountered are repaired, it is time to test the control. To test the control, add a new web site project to the web control library project currently open. Once the test web site has been created, set the test project as the start up project by right clicking on the web site solution in the Solution Explorer and selecting the “Set as Start Up Project” menu option. Next, locate the Default.aspx page in the web site solution, right click on this page, and select the “Set as Start Page” menu option.

If you downloaded the project, you can configure a virtual directory pointing at the example website, and examine it instead of creating one from scratch. The example project contains two subordinate projects, a web class library with the single custom web control (MOEbutton), and a sample website with additional files needed to support the demonstration.

If you configure the sample project and start the default page, you will see a collection of MOEbutton controls arranged at the top of the page in a manner similar to a toolbar. The controls each have a mouse over effect which consists of an alternate version of the normal icon, and some JavaScript calls, some to launch an alert, and one to open a new window.

Aside from the properties created in support of the MOEbutton class, as the class inherits from the WebControl class, all of the properties and methods of that class are also included at no extra charge. Therefore, it requires no additional effort to permit the control user to set the background color or border characteristics, or to define tooltips without writing any additional code.

Once the site is up and running, you should observe the following displayed in your browser window:

Image 4

Figure 3: MOE Button Example in Internet Explorer

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionImageUrl is not a member of Htmlcontrols.Htmlinputimage [modified] Pin
PCAssist_Northwest16-Jul-09 9:24
PCAssist_Northwest16-Jul-09 9:24 
GeneralMOE Button Pin
engr-harv22-Aug-06 8:20
engr-harv22-Aug-06 8:20 
GeneralRe: MOE Button Pin
engr-harv24-Aug-06 4:26
engr-harv24-Aug-06 4:26 
QuestionHow about... Pin
Simon Hughes22-Aug-06 2:05
Simon Hughes22-Aug-06 2:05 
AnswerRe: How about... Pin
salysle22-Aug-06 4:23
salysle22-Aug-06 4:23 
GeneralRe: How about... Pin
Simon Hughes22-Aug-06 4:39
Simon Hughes22-Aug-06 4:39 
AnswerI've found out how to do it using the standard ImageButton Pin
Simon Hughes24-Aug-06 0:28
Simon Hughes24-Aug-06 0:28 
GeneralNo You Didn't Pin
Oakman29-Dec-06 6:59
Oakman29-Dec-06 6:59 

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.