@bobnoordam

Raising an event on a usercontrol, and subscribing to it from an ASPX page

This is a minimalistic demonstration on hooking into an event risen by a usercontrol. The main page subscribes to the event on the user control, and once the usercontrol raises a postback the event data is retrieved.

User control code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace UsercontrolEvents
{
    public partial class WebUserControl1 : System.Web.UI.UserControl
    { 
        public delegate void SendEventHandler(string message); 
        protected void Page_Load(object sender, EventArgs e)
        { 
        }
 
        public event SendEventHandler SendEvent;
        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (SendEvent != null) SendEvent(DropDownList1.SelectedValue);
        } 
    }
}

User control markup

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="UsercontrolEvents.WebUserControl1" %>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
    <asp:ListItem>One</asp:ListItem>
    <asp:ListItem>Two</asp:ListItem>
    <asp:ListItem>Three</asp:ListItem>
</asp:DropDownList>

Main page code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace UsercontrolEvents
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
 
 
            WebUserControl1.SendEvent += delegate(string message)
                {
                    LabelMainPage.Text = message;
                };
 
        }
    }
}

Main page markup

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UsercontrolEvents.Default" %>
 
<%@ Register Src="~/WebUserControl1.ascx" TagPrefix="uc1" TagName="WebUserControl1" %>
 
 
<!DOCTYPE html>
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        This is the main page. The label below will get it's value from subscribing to an event on the user control.
        <asp:Label ID="LabelMainPage" runat="server" Text="Label"></asp:Label>
         
         
        <hr/>
        <uc1:WebUserControl1 runat="server" id="WebUserControl1" />
    </div>
    </form>
</body>
</html