Friday, February 12, 2010

Bubbling up events from user control to parent page/control

It is a good practice to use user controls when same controls are repeated in many pages. But there are some cases where the user control has some controls which generate events and those need to be handled by the containing page/user control. For eample there is a button control in the user control and you want to do something in parent page/control when the button in user control is clicked. In this case

1.You need to define an event handler in user conrol as shown below.

public partial class UC_Pagination : System.Web.UI.UserControl
{
...
...

public event EventHandler PageIndexChanged;
...
...
...
}


2. You need to call the event explicitly in the user control's implementation of the event handler of button click as shown here

public partial class UC_Pagination : System.Web.UI.UserControl
{
...
...
protected void Button1_Click(object sender, EventArgs e)
{
...
...
PageIndexChanged(sender, e);
...
...
}
...
...
...
}

3. Implement the event handler bubbled up by user control in the parent page/control in its own way as usual (shown below).


public partial class Coaches : System.Web.UI.Page
{
...
...
protected void ucPaginationPageIndexChanged(object sender, EventArgs e)
{
...
...
...
}

...
...
}

kick it on DotNetKicks.com
Shout it

1 comments:

Kiran said...

Good. Nice one.