UserControl event handler does not fire

I am dynamically loading a UserControl into a view that is in a MultiView control. Although UserControl adds an event handler, the event never fires.

What am I missing here? Thanks!

Contains an 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 } 
+6
c # events user-controls
source share
4 answers

I think this does not work because you are loading the control into the prerender event on the page. After the postback, the control is lost because it has no view state. Therefore, there is no control to trigger his event. Try loading the control into the init event. Let us know what will happen!

+8
source share

Reverse transaction processing is done before rendering, so the control is not on the page in your case.

Lifecycle events are fired in this order (several are missing):

  • Init
  • Load
  • Prerender
  • Unload

And event processing is performed between Load and PreRender (in case some events change the way the page is displayed, this makes sense).

So, just move your code that loads the Retry control to load or initialize.

Link: Asp.Net Page Lifecycle Overview

+6
source share

The control must first be visible so that it can enter the OnPreRender event. but perhaps you want this to be impossible. make sure EnableViewState = false;

+2
source share

It seems like the control is not added after every post back, I would take out the if statement on the contained aspx page to find out if this fixes the problem ... im assuming Retry is a button?

+1
source share

All Articles