Welcome to Bilal Haidar [MVP, MCT] Official Blog Sign in | Join | Help

Define a Custom Event inside UserControls

If you are working with either a new custom server control or a normal web user control, this is the proper way of adding an event that can be handled by the parent control of the child control you are develping:

Add the following to the control (Server Control / Web User Control ) being developed:

#region Event Handler 
private static readonly object EventBubbleRaised = new object(); 
public event EventHandler BubbleRaise 
{ 
       add 
      { 
                Events.AddHandler(EventBubbleRaised, value); 
       } 
       remove 
      { 
               Events.RemoveHandler(EventBubbleRaised, value); 
      } 
} 
protected virtual void OnBubbleClick(EventArgs e) 
{
              EventHandler BubbleRaised = (EventHandler)Events[EventBubbleRaised]; 
              if (BubbleRaised != null) 
                      BubbleRaised(this, e); 
} 
#endregion

In the parent page / control, you add this in the Init method:

BubbleControl.BubbleRaise += new EventHandler(ControlName_BubbleRaise);


Then you define you our handler:

private void ControlName_BubbleRaise(object sender, EventArgs e) 
{ 
                Response.Write(sender.GetType().ToString()); 
}

That was a simple example, but at least you know now the steps.

Regards

Published Wednesday, April 12, 2006 10:51 PM by BilalHaidar [MVP]

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# re: Define a Custom Event inside UserControls

Excellent excellent. Wish I saw this blog earlier
Tuesday, April 25, 2006 2:55 AM by liming

Leave a Comment

(required) 
required 
(required)