rick schott
rick schott

Reputation: 20617

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"/>

Upvotes: 4

Views: 4285

Answers (2)

Rex M
Rex M

Reputation: 144112

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
}

Upvotes: 8

TJB
TJB

Reputation: 13497

I would recommend specifying a strongly typed master page in your content page and exposing the event on the master page side

Here's a good MSDN reference

This is similar to what Rex M specified but just simplifies accessing the Master Page a little bit.

// Master Page Code
public event EventHandler ClearClick
{
   add
   {
      this.btnClear.Click += value;
   }
   remove
   {
      this.btnClear.Click -= value;
   }
}

// Content Page markup
<%@ Page  masterPageFile="~/MasterPage.master"%>

<%@ MasterType  virtualPath="~/MasterPage.master"%> 

// Content Page Code
protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    this.Master.ClearClick += new EventHandler(OnClearClick);
}

private void OnClearClick(object sender, EventArgs e)
{
   // Handle click here
}

Upvotes: 1

Related Questions