How to Create an Event in ASP.NET User Control
Let’s assume we have a control ShippingSelect.ascx and we would like to assign an event like ItemCommand.
Firstly we add a new User Control to our project (ShippingSelect.ascx) and at the code behind we need to declare the name of the event using the EventHandler<TEventArgs> where TEventArgs is an EventArgs that contains the event data.
namespace Examples.EShop
{
public partial class ShippingSelect : System.Web.UI.UserControl
{
/// Create OnItemCommand event
public event EventHandler<ShippingEventArgs> ItemCommand;
protected void Page_Load(object sender, EventArgs e)
{
}
}
/// <summary>
/// Event arguments for the Command Type,
/// Address that user wants to dispatch his order
/// and the Shipping Method user wants to use
/// </summary>
public class ShippingEventArgs : EventArgs
{
public enum CommandType { Insert, Update, Delete, Select}
public CommandType Command { set; get; }
public Address Address { set; get; }
public ShippingMethod ShippingMethod { set; get; }
}
}
Now let’s see how we can use this control and call the event we previously assigned to:
We Create a control CheckOutProcess.ascx that contains the above ShippingSelect.ascx control.
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="CheckOut.ascx.cs" Inherits="Examples.EShop.CheckOutProcess" %> <%@ Register TagPrefix="example" TagName="ShippingSelect" Src="~/Controls/CheckOut/ShippingSelect.ascx" %> <example:ShippingSelect ID="shippingSelect" runat="server" OnItemCommand="shippingSelectItemCommand" />
And at the code behind of CheckOutProcess.ascx we can handle the shippingSelectItemCommand
protected void shippingSelectItemCommand(object sender, ShippingEventArgs e)
{
switch (e.Command)
{
case ShippingEventArgs.CommandType.Select:
{
//TODO: Handle Select Command
}
break;
}
}