User Control Bubble Event

A better idea is to publish an event in the user control to allow any interested parties to handle the event.

This technique is commonly referred to as “event bubbling”.

Here is an exmple:

<%@ Control Language=”C#” AutoEventWireup=”true” CodeBehind=”UserControlDemo.ascx.cs” Inherits=”WellnGood.UserControlDemo” %>
<asp:Button ID=”btn1″ runat=”server” Text=”Bubble to Page”
onclick=”btn1_Click” />

public partial class WebUserControl : System.Web.UI.UserControl

{

public event EventHandler buttonClick;

protected void Button1_Click(object sender, EventArgs e)
{
buttonClick(sender, e);
}

}

Then you can subscribe the event buttonClick at webpage to display the different information .

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”BubbleEvent.aspx.cs” Inherits=”WellnGood.BubbleEvent” %>

<%@ Register Src=”~/UserControlDemo.ascx” TagName=”UserControlDemo” TagPrefix=”ucDemo” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

<html xmlns=”http://www.w3.org/1999/xhtml&#8221; >
<head runat=”server”>
<title>Untitled Page</title>
</head>
<body>
<form id=”form1″ runat=”server”>
<div>
<ucDemo:UserControlDemo ID=”ucDemo1″ runat=”server” />
</div>
</form>
</body>
</html>

public partial class BubbleEvent: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

ucDemo1.buttonClick+=new EventHandler(ucDemo1_buttonClick);

}

protected void ucDemo1_buttonClick(object sender, EventArgs e)
{
Response.Write(“I am User control bubble event on Page”);
}

}

Leave a comment

Filed under .Net

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s