steve jobs
steve jobs

Reputation: 97

Loading ASP.NET user control at run time

I have an ASP.NET user control with a button, and I want to add it to the page when the user clicks a button from another user control. I have created an event handler to the first user control to handle it from the page and add the second user control to a page. Everything is working normally, but the button on the second user control doesn't respond to the event.

I place the second control on RadAjaxPanel

Note: When I add the second user control at design time its working fine.

Upvotes: 0

Views: 872

Answers (1)

bgs264
bgs264

Reputation: 4642

All dynamically created controls should be added by the end of Page_Init (though sometimes you can get away with them added by the end of Page_Load).

If you're only adding them based on a button click event then you've done this in the event handers which fire AFTER Page_Init and Page_Load in the lifecycle - This is why your events don't fire and why it works fine when you add at design time.

This is because when a button is clicked on the second user control - the whole page lifecycle starts again. The page goes through Page_Load and Page_Init first and your control doesn't get loaded here. So, when the page lifecycle handles the "handle postback events" part, the control no longer actually exists, so the event doesn't fire.

Conversely, when you add at design time, the control exists in Page_Init and Page_Load so is able to handle the postback events from the user control because it already exists in the control tree - if this makes sense.

You need to think how you can restructure so they're added by the time Page_Load has finished at the very latest or it won't work. Without code samples or more detail it's hard to suggest exactly how you might do this. One possibility would be to set it visible instead of loading it outright - but if the control does some 'heavy lifting' on load like database hits or API calls then this might not be suitable for you.

I did something similar. What I did was to load some controls dynamically based on a selection from a DropDownList. If you have a method which loads the control for you, let's call it LoadControls(), then you can do something like this:

DropDownList_Click {
 ViewState("LoadControls") = true;
 LoadControls()
}

By setting the ViewState variable, you can then indicate Page_Load to load the controls on future postbacks:

Page_Load {
 if (ViewState("LoadControls") == "true")
 {
  LoadControls();
 }
}

This has the effect of then loading the control on-the-fly when the event first happens, and then at future times in the lifecycle.

Upvotes: 3

Related Questions