Saturday, November 6, 2010

Raising event from webcontrol to host page

A simple way to raise an event from a webcontrol to the host aspx page in c#

1. Ok, in your web control at the top define the bubble event:

public partial class webcontrols_rightnav : System.Web.UI.UserControl
{
#region BubbleEvents
public event EventHandler MyUserControlEvent;
#endregion BubbleEvents

....

2. Next in one of your web control functions etc raise the event:

if (MyUserControlEvent!= null) //i.e. the host page is subscribing to the event!
{
//raise event
MyUserControlEvent(this, e);
}

3. In your host page...

Add the event handler:

rightnav1.MyUserControlEvent += new EventHandler(DoSomething);

4. Add the function to handle the event in the host page

protected void DoSomething(object sender, EventArgs e)
{
//
}


** important - one thing that catches me out is putting the ...+= new EventHandler(DoSomething); code in a !IsPostBack piece of code - this will only then fire on page load, which is probably NOT what you want!

...Hope this helps!