views:

21

answers:

1

There is nothing fancy with the mark-up:

<hr />
Add... <asp:Button ID="buttonTextSegment" runat="server" Text="Text Segment" 
    onclick="buttonTextSegment_Click" />
<hr />

Or the code:

protected void buttonTextSegment_Click(object sender, EventArgs e)
{
   //never is triggered
}

My guess is that it is due to the hierarchy/load order:

In English: Inside the page's Load, it adds a user control. Inside of that user control, inside of Page_LoadComplete (is this the issue!?), it adds another user control, it is the inner-most user control that contains the mark-up button.

Pseudo Visually: Page -> Page_Load: Dynamically Added User Control -> Page_LoadComplete: Another Dynamically Added User Control -> User Control Mark-Up: Button with event.

Do events need to be hooked before LoadComplete? (Is there a way to make events still work even though the controls are added in LoadComplete?)

A: 

You should create the user controls in this order Page -> Page_Init: Dynamically Added User Control -> Page_Init: Another Dynamically Added User Control -> User Control Markup.

If you do them in the Page_Load or Page_LoadComplete functions then they are created too late for the event handlers as the event handlers are fired directly after the LoadControlState event - which happens between the Page_Init and the Page_Load events.

David Williams
What if I need controls added due to a button click? Where a button click's effect only appears after Page_LoadComplete (due to a page's lifetime)?
Yerg
According to the ever-popular page-lifecycle article (http://msdn.microsoft.com/en-us/library/ms178472.aspx), postback events are fired after Page_Load. So theoretically, if you create/add your controls in Page_Load, that should be ok. However, you're correct: OnLoadComplete is after postback events are fired, so creating controls there would be too late.
mikemanne
To be specific, you CAN add controls in LoadComplete, they will show up. However, any events hooked to them DO NOT WORK. The question is: why?
Yerg
If you add the controls in LoadComplete (or for that matter any time prior to RenderComplete) the controls WILL appear. However, you will not be able to respond to the events, as the event handlers will not be available after postback due to you having to first recreate the controls before the event can be handled. Does that make more sense?
David Williams
I get it. But it creates the perfect storm of insanity: http://stackoverflow.com/questions/3622479/asp-net-life-cycle-dichotomy-dynamically-added-controls-and-events where the goals' (dynamically adding controls that contain events) solutions contradict each other, causing a chicken-or-the-egg issue.
Yerg