Click here to Skip to main content
15,884,794 members
Articles / Web Development / HTML

How to Create an Event for a User Control

Rate me:
Please Sign up or sign in to vote.
4.00/5 (7 votes)
16 Oct 2009CPOL2 min read 86K   1.9K   24   3
Article on how to create a user defined event for a user control

Introduction

In this article, I will try to explain how to create user defined events for user control and how to raise them. It does not require a lot of expertise and can be done very easily. For a complete working copy of this article, download the project attached with this article.

Background

There are various scenarios in which we would like to create events for user controls and we expect them to be raised when something is done.

How to

In this example, I will be performing some mathematical calculations (Add, Subtract, Multiply, Divide) using an ASPX page, a user control, two user defined classes Enum and OperationEventArgs. I believe that you are familiar with the terms ASPX page and user control. I will explain about my two classes. Enum is just a class that contains the enumeration for the mathematical operation my control will perform and it looks something like this:

C#
public enum Operation{ Addition = 1, Subtraction = 2, Multiplication = 3, Division = 4 };

My second user defined class is OperationEventArgs which inherits System.EventArgs. I create this class to pass the arguments based on my requirements. The class contains some public properties to hold certain values and will be treated as arguments of OperationEventArgs. It looks something like this:

C#
/// <summary>
/// Class that will represent Operation related event arguments
/// </summary>
public class OperationEventArgs : EventArgs
{
    private Operation _operationType;
    private decimal _operationResult;
    
    public OperationEventArgs()
    {
        
    }
    
    /// <summary>
    /// Constructor with parameters to initialize values
    /// </summary>
    /// <param name=""operationType"">Operation</param>
    /// <param name=""result"">decimal</param>
    public OperationEventArgs(Operation operationType, decimal result)
    {
        this._operationType = operationType;
        this._operationResult = result;
    }
    
    /// <summary>
    /// Property to get/set operation type
    /// </summary>
    public Operation OperationType
    {
        get
        {
            return this._operationType;
        }
        set
        {
            this._operationType = value;
        }
    }
    
    /// <summary>
    /// Property to get/set operation result
    /// </summary>
    public decimal OperationResult
    {
        get
        {
            return this._operationResult;
        }
        set
        {
            this._operationResult = value;
        }
    }
}    

You will understand the usage of these classes better when you will see them working in the example. The user control in this example contains two TextBox controls and one Button. The following code creates a public event for the UserControl.

C#
//Delegate that will be the pointer for the event, contains two arguments 
//sender (object that raised it) and OperationEventArgs for the event arguments
public delegate void CalculationInProgress(object sender, OperationEventArgs e);
//Event name 
public event CalculationInProgress Calculating;    

In this example, I am raising the events on the button click's event but in order to raise an event, it's not necessary that they will be raised on any other event. You can also raise them after some operation is done or according to your requirements.

The following code is written on the button's click event:

C#
protected void btnPerformOperation_Click(object sender, EventArgs e)
{
    //In the following lines which will perform the mathematical operations
    //you will notice that a new object of OperationEventArgs is created 
    //and the values are passed to its constructor
    
    //performs the addition operation and raise the event
    this.Calculating(this, new OperationEventArgs
    	(Operation.Addition, Convert.ToDecimal(this.txtValue1.Text) 
    	+ Convert.ToDecimal(this.txtValue2.Text)));
    //performs the subtraction operation and raise the event
    this.Calculating(this, new OperationEventArgs
    	(Operation.Subtraction, Convert.ToDecimal(this.txtValue1.Text) 
    	- Convert.ToDecimal(this.txtValue2.Text)));
    //performs the multiplication operation and raise the event
    this.Calculating(this, new OperationEventArgs
    	(Operation.Multiplicaiton, Convert.ToDecimal(this.txtValue1.Text) 
    	* Convert.ToDecimal(this.txtValue2.Text)));
    //performs the division operation and raise the event
    this.Calculating(this, new OperationEventArgs
    	(Operation.Division, Convert.ToDecimal(this.txtValue1.Text) / 
    	Convert.ToDecimal(this.txtValue2.Text)));
}    

That's all to be done in the user control.

The code you need to place in the ASPX file looks like this:

ASP.NET
<%@ Page Language="C#" 
	AutoEventWireup="true"  CodeFile="Default.aspx.cs" 
	Inherits="_Default" %>
<%@ Register Src="~/ctrlCalculator.ascx" TagPrefix="
	Calculator" TagName="Calculation" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 
	Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
    <body>
        <form id="form1" runat="server">
            <div>
                <%-- user defined control that will perform the mathematical 
		operation notice that the event which we created can be seen here --%>
                <Calculator:Calculation ID="ctrlCalculartor" runat="server" 
		OnCalculating="ctrlCalculator_Calculating"></Calculator:Calculation>
            </div>
        </form>
    </body>
</html>    

In the following code, I actually wrote the event handler on my aspx.cs file:

C#
/// <summary>
/// Event handler for the user defined event
/// </summary>
/// <param name=""sender"">object</param>
/// <param name=""e"">OperationEventArgs</param>
protected void ctrlCalculator_Calculating(object sender, OperationEventArgs e)
{
    //In this event handler you will notice that we can access 
    //the properties we created in the OperationEventArgs class 
    //that will provide the values assigned to them while raising event
    Response.Write(string.Format("The result of \"{0}\" 
    	operation is : {1}", e.OperationType, e.OperationResult));
}    

That's it!!!

You can now run your application and provide values to the TextBox. Suppose I entered these values 4 and 2. When the button will be clicked, you will see the following output based on the supplied values.

Summary

In this article, we tried to create an event for the user control which will be raised on certain mathematical operations. We used an enumeration to get the operation and a user defined class OperationEventArgs to get the required arguments for the event.

I hope this article delivers the idea easily of how you can create user defined event for a user control.

History

  • 16th October, 2009: Initial post

License

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


Written By
Web Developer
United Arab Emirates United Arab Emirates
Faraz is working as a Senior Software Engineer for a company located in Sharjah, UAE. He likes developing new applications with the latest technologies. Mostly reponsible for web applications using Microsoft.Net. He has done MCPD so far. Other than work play guitars, sing and play PSP.

Comments and Discussions

 
QuestionNullReference check before throwing the event? Pin
Bernd T.19-Oct-09 22:35
Bernd T.19-Oct-09 22:35 
AnswerRe: NullReference check before throwing the event? Pin
TobiasP9-Nov-09 2:40
TobiasP9-Nov-09 2:40 
In a multi-threaded application, I believe that isn't enough: It is possible for all event handlers to unsubscribe between the null reference check line and the event raising line.
GeneralRe: NullReference check before throwing the event? Pin
C.Shivashankar13-Sep-12 22:53
C.Shivashankar13-Sep-12 22:53 

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.