Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling User Control Events on Containing Page

I want to have a user control containing a save button.

I want the click event attached to the save button to be handled by the containing page not the user control

Is this possible?

EDIT MORE SPECIFIC

Say I have a page called "Editor Page" and a user control called "Editor Buttons". On the "Editor Buttons" user control I have a save button (which is a web control). I want the Click event of the save button to be handled by the "Editor Page" rather than the user control.

The reason for this is because I want to specify base pages that implement common behaviour.

like image 823
AJM Avatar asked Jun 03 '09 09:06

AJM


2 Answers

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

Here is an exmple:

public partial class Test : 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 .

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

 UserControlID.buttonClick+=new EventHandler(UserControlID_buttonClick);

}

protected void UserControlID_buttonClick(object sender, EventArgs e)
 {
     Response.Write("hello,I am jack.");
 }

}
like image 84
Santosh Wavare Avatar answered Sep 29 '22 08:09

Santosh Wavare


I will assume that you have the code for the UserControl. If that is the case, you can define a Save event in your user control and have it expose the Click event of the save button, either directly, or by internally setting up an event handler and raise the Save event when the button is clicked. That could look something like this in the UserControl:

public event EventHandler Save;

private void SaveButton_Click(object sender, EventArgs e)
{
    OnSave(e);
}

protected void OnSave(EventArgs e)
{
    // raise the Save event
    EventHandler save = Save;
    if (save != null)
    {
        save(this, e);
    }
}
like image 26
Fredrik Mörk Avatar answered Sep 29 '22 07:09

Fredrik Mörk