0

How can we find the control that fired inside of a Master page that also has a panel from code behind? I have the following layout.

Master Page
+---------Panel-----------+
| TextBox  Button1 Button2|
+-------------------------+
|
-------->Child Page
              +-------------------------+
              |        Get From Here!   |
              +-------------------------+

When I try the following the targetId is empty

if (IsPostBack)
{
    var targetID = Request.Form["__EVENTTARGET"];

    if (targetID != null && targetID != string.Empty)
    {
    var targetControl = this.Page.FindControl(targetID);
    }
}

I want to find out which button caused post back.

****Update****

I've tried the following link below without sucess.

Find on Page Init

Community
  • 1
  • 1
TheCodingCat
  • 125
  • 2
  • 6
  • possible duplicate of [On postback, how can I check which control cause postback in Page\_Init event](http://stackoverflow.com/questions/3175513/on-postback-how-can-i-check-which-control-cause-postback-in-page-init-event) – Luizgrs Oct 08 '14 at 17:51
  • Already tried the recommendations those don't work. – TheCodingCat Oct 08 '14 at 18:41

1 Answers1

0

You can use an event that your MasterPage offers to communicate with the Page.

Within your MasterPage create something like these

public event EventHandler Button1ClickEvent;
public event EventHandler Button2ClickEvent;

What is going on here is that you are creating an event that the MasterPage can check for a page that is listening for and fire an event to that page to signal that is has been called. In this case EventHandler means that you'll be passing EventArgs to the event listener.

You send an event by doing this

protected void Button1_Click(object sender, EventArgs e)
{
    if (Button1ClickEvent != null) // check if a sub page is implementing it
        Button1ClickEvent(this, EventArgs.Empty); // fire the event off
}

protected void Button2_Click(object sender, EventArgs e)
{
    if (Button2ClickEvent != null)
        Button2ClickEvent(this, EventArgs.Empty);
}

Next, wire up your Page to implement these events

Add in this to your Page definition

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

Now you can access these events in your page code-behind

private void Master_Button1Click(object sender, EventArgs e)
{
    // This is called when the `Button1ClickEvent` is fired from your MasterPage
}

private void Master_Button2Click(object sender, EventArgs e)
{
    // This is called when the `Button2ClickEvent` is fired from your MasterPage
}

protected void OnInit(EventArgs e)
{
    // Setup an event handler for the buttons
    Master.Button1ClickEvent += new EventHandler(Master_Button1Click);
    Master.Button2ClickEvent += new EventHandler(Master_Button2Click);
}
Kirk
  • 16,182
  • 20
  • 80
  • 112