FAHNZ

MODE

Bubbling UserControl Events

This scenario has bitten me before. User control events fire after page events. This can be a problem if an update within the user control needs to be reflected in the outer page container. The solution is to “bubble” the event from the user control into the page so it can react accordingly. So, as much for my reference as anyone else’s, here’s some quick ‘n dirty code to bubble events from an ASP.NET user control to the page that contains it:

User Control Code:

public partial class SamplePage : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    // "SampleUserControl1" is the ID of the control that has already been placed in the HTML of the page
    SampleUserControl1.BubbleEventHappened += new EventHandler(BubbleEventHappened);
  }

  private void BubbleEventHappened(object sender, EventArgs e)
  {
    // code to react to bubbled event goes here
  }
}

Page (that contains the User Control) Code:

public partial class SamplePage : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    // "SampleUserControl1" is the ID of the control that has already been placed in the HTML of the page
    SampleUserControl1.BubbleEventHappened += new EventHandler(BubbleEventHappened);
  }

  private void BubbleEventHappened(object sender, EventArgs e)
  {
    // code to react to bubbled event goes here
  }
}

There. That wasn’t so bad!


Comments are closed.