Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserControl's Event Handler not firing

I dynamically load a UserControl into a View that's in a MultiView control. Although the UserControl adds an event handler, the event never fires.

What am I missing here? Thanks!

Containing ASPX page:

protected override void OnPreRender(EventArgs e)
{
    if (MultiView1.ActiveViewIndex == 2) //If the tab is selected, load control
    {
        Control Presenter = LoadControl("Presenter.ascx");
        (MultiView1.ActiveViewIndex.Views[2].Controls.Add(Presenter);
    }
    base.OnPreRender(e);
}

Presenter.ascx.cs

override protected void OnInit(EventArgs e)
{
    Retry.Click += this.Retry_Click; //This is a .Net 2.0 project
    base.OnInit(e);
}


protected void Retry_Click(object sender, EventArgs e)
{
    //This never fires
}
like image 487
Mark Maslar Avatar asked Apr 27 '09 14:04

Mark Maslar


2 Answers

I am thinking it is not firing because you are loading the control in your page's prerender event. Upon postback, the control is being lost because there is no view state for it. Therefore there is no control to fire its event. Try to load the control in the page's init event. Let us know what happens!

like image 110
Dan Appleyard Avatar answered Sep 28 '22 06:09

Dan Appleyard


Postback event handling is done before rendering so the control is not present in the page in your case.

The life cycle events are fired in this order (skipped a few):

  1. Init
  2. Load
  3. PreRender
  4. Unload

And event handling is done between Load and PreRender (in case some events change the way the page should be rendered, it makes sense).

So just move your code that loads the Retry control to Load or Init.

Reference: Asp.Net Page Life Cycle Overview

like image 27
mbillard Avatar answered Sep 28 '22 08:09

mbillard