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#" 
    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
    <form id="form1" runat="server">
        <active:uc runat="server" ID="ucUserControl" OnButtonClicked="ButtonClicked" />

No comments:

iPhone Launch Screen Sizes

iPhone Portrait iOS 8 Retina HT 5.5 = 1242 X 2208 Retna HD 4.7 = 750 X 1134 iPhone Landscape iOS 8 Retina HD 5.5  2208 X 1242 iPho...