Click here to Skip to main content
Click here to Skip to main content

How to Create an Event for a User Control

, 16 Oct 2009
Rate this:
Please Sign up or sign in to vote.
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:

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:

/// <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.

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

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:

<%@ 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:

/// <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)

Share

About the Author

farazsk11
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? PinmemberBernd T.19-Oct-09 22:35 
AnswerRe: NullReference check before throwing the event? PinmemberTobiasP9-Nov-09 2:40 
GeneralRe: NullReference check before throwing the event? PinmemberC.Shivashankar13-Sep-12 22:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140827.1 | Last Updated 16 Oct 2009
Article Copyright 2009 by farazsk11
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid