Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass MasterPage ImageButton event to content Page

I have ImageButton in a MasterPage. I want the OnClick event to fire and be captured by the .ASPX page hosted inside the MasterPage?

MasterPage:

<asp:ImageButton ID="btnClear" OnClick="Clear_Click" 
 ImageUrl="images/Back_Icon_06.png" runat="server" AlternateText="Clear" 
 width="38"   height="39"/>
like image 902
rick schott Avatar asked Jan 23 '23 02:01

rick schott


1 Answers

The masterpage is actually a child of the page (in fact, it's a UserControl). We don't want the page to have to be aware of the intimate details of its child controls (thats why we delegate those aspects to those controls in the first place), so the correct approach would be to handle the click event on the master page and from there fire another event on the masterpage which the page handles:

Master:

public event EventHandler SomethingHappened;

protected void Button_Click(object sender, EventArgs e)
{
    OnSomethingHappened(EventArgs.Empty);
}

protected void OnSomethingHappened(EventArgs e)
{
    if(this.SomethingHappened != null)
    {
        this.SomethingHappened(this, e);
    }
}

Page:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    //allows us to change master pages
    if(this.Master is MyMaster)
    {
        ((MyMaster)this.Master).SomethingHappened += new EventHandler(HandleSomethingHappened);
    }
}

private void HandleSomethingHappened(object sender, EventArgs e)
{
    //deal with it
}
like image 170
Rex M Avatar answered Jan 31 '23 02:01

Rex M