Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

How to Create an Event for a User Control

4.00/5 (7 votes)
16 Oct 2009CPOL2 min read 86.7K   1.9K  
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)