views:

620

answers:

2

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"/>
+2  A: 

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
}
Rex M
Very nice, I do this with UserControls and Pages(have answered SO questions on it..lol) but wasn't sure with the MasterPage. The explanation is appreciated; I didn't know it was treated just like a UserControl. The additional MyMaster check is a nice addition.
rick schott
+1  A: 

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
}
TJB
I would discourage creating a "pass-through" event - the page should never know about particular elements or their own events in another class. Rather, the button click event in the masterpage should signify something more significant has happened - for example, the purpose of the button click.
Rex M