user153923
user153923

Reputation:

Add EventHandler to Content Page

I have wired up the Button control on my Master Page in the Content Page as follows:

SiteMaster MasterPage;

protected void Page_Load(object sender, EventArgs e) 
{
   if (!Page.IsPostBack) 
   {
      MasterPage = (SiteMaster)Page.Master;
      MasterPage.Button1.Click += new EventHandler(Button1_Click);
   }
}

void Button1_Click(object sender, EventArgs e) 
{
   MasterPage.Button1_Click(sender, e);
}

However, whenever I click Button1 on the page (running under localhost), the Page_Load event fires!

What have I done wrong?

If it helps, the MasterPage.Button1_Click event runs a log in script, so there should be no recursive calls.

Upvotes: 1

Views: 1579

Answers (2)

jdavies
jdavies

Reputation: 12894

Is the issue here that the handler Button1_Click is not firing for you?

If so, the reason for this is because you are only assigning the event handler for the Click event on initial page load and not when the page is posting back.

Try assigning the event handler on initial load and subsequent postbacks like so:

protected void Page_Load(object sender, EventArgs e)
{
    MasterPage = (SiteMaster)Page.Master;
    MasterPage.Button1.Click += new EventHandler(Button1_Click);
}

Hope this helps.

Upvotes: 2

Frank Hale
Frank Hale

Reputation: 1896

Perhaps you want to wire your event up in the Page_Init as opposed to the Page_Load.

as far as your button click causing Page_Load to fire. Page_Load is always going to get fired because it's part of the page lifecycle.

see: http://support.microsoft.com/kb/305141 for page lifecycle details.

Page_Init: During this event, you can initialize values or connect any event handlers that you may have.

see also question: In asp.net, page_load occuring before radio button OnCheckedChanged event

Upvotes: 1

Related Questions