Events inside dynamically created user controls do not fire

I have a UserControl let's call it ButtonPanel which is simply a button (id="btn") within a panel (id="bPanel"), and a Literal (id="msg"). The button's click event bound to the event handler ("btn_Click") in the ASPX tag for the button. The handler simply puts "Button Pressed" into the aforementioned "msg" Literal.

In my main page, if I drag a ButtonPanel into the page rather than dynamically create it, then when the event is fired within the control, and the message is shown. All works as expected.

However, if I dynamically create the ButtonPanel inside the main page's Page_Init() function and add it to a container on the page, then the btn_Click event handler in the control is never called. The user control's Page_Load() and Page_Init() functions are both called by the PostBack, but the event handler within the UserControl never gets called after that.

One would think that the id of "btn" would be included in the postback data but I have been unable to find it in Request.Params. I wouldn't mind dispatching the event myself if I could just figure out which control within the user control was involved, and what event was involved. After all not everything is a button and a click event.

I've been searching the web and of course i'm far from the first person to run across this. I haven't found any good solutions thus far.

And if anybody from Microsoft is reading this... WTF? ASP.NET has been around for how many years now? Nearly 20, I think? This fundamentally breaks the usefulness of user controls so why haven't you addressed it?

EDITS: Added some detail from subsequent comments.

1 answer

  • answered 2018-11-08 08:25 SazooCat

    Have you mapped the event handler function to the event?

    When you drag it on to the page and add the click event attribute or code behind handler it does the equivalent of this behind the scenes for you.

    When you add it dynamically you have to tell it to map the event to the handler function.