Tuesday, June 22, 2010

How to bubble up an event from usercontrol to parent page(control) (Part 1 - With Delegates)- Asp.net

This article demonstrate how to bubble up events from user-control to parent page or control. To bubble up event I use event and delegate.

Please note: If you add a event called ButtonClicked to the usercontrol, in the markup, .net convert it to OnButtonClicked

UserControl : Code
public partial class ActiveUserControl : UserControl
{
    public event EventHandler ButtonClicked;
    protected void InvokeButtonClicked(object sender, EventArgs e)
    {
        if (this.ButtonClicked != null)
            this.ButtonClicked(sender, e);
    }
}

Control : Markup
<%@ Control Language="C#" 
    AutoEventWireup="true" 
    CodeBehind="ActiveUserControl.ascx.cs" 
    Inherits="ActiveTest.UserControls.ActiveUserControl" %>
<asp:Button runat="server" ID="btnButton" Text="Button" OnClick="InvokeButtonClicked" />

Consuming page:

<%@ Page Language="C#" %>
<%@ Register TagName="uc" TagPrefix="active" Src="~/UserControls/ActiveUserControl.ascx" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script runat="server"> 
        protected void ButtonClicked(object sender, EventArgs e)
        {
            ///
            /// Bubbled up event
            ///
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <active:uc runat="server" ID="ucUserControl" OnButtonClicked="ButtonClicked" />
    </form>
</body>
</html>
 

No comments:

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...