A: If you are just rotating advertisements on a page, using LoadControl is simple.
If you have a complex control with ViewState and events firing duringĀ postback, then LoadControl is difficult. It's not just LoadControl either - newing up a server side control and adding it to a Controls collection is also tricky.
ASP.NET provides a thick layer of abstraction for building web applications, but dynamically loading controls requires intimate knowledge of what is happening underneath the covers. You'll need to know the page lifecycle inside and out. You'll need to know how ViewState works, and how the runtime raises postback events. It takes some time, experience, trail, and error.
Here is a tip: keep it simple. I've seen developers overly complicate pages with dynamically loaded controls. In some scenarios, we can get the same behavior by adding the controls in markup and toggling the Visible property. The page is easier to test and modify, and generally will have fewer bugs.
Also, this "feature" doesn't have a bad design, really. You have to realize before going down this path that you'll be shouldering many responsibilities for your control that ASP.NET would otherwise take care of. It would be difficult for Microsoft to provide a general-purpose solution to dynamically loaded controls (but they might be able to cover 60% of the use cases).
If you still need dynamic controls, then read everything Scott Mitchell writes:
Dynamic Controls in ASP.NET
Working With Dynamically Created Controls
Dynamic Web Controls, Postbacks, and View State
Control building and ViewState Redux
Tip: When Adding Dynamic Controls, Specify an ID
Comments
The project I've been on for the past 2.5 years had an architecture based on IBuySpy Portal when I started (and was assigned as architect)... and I immediately told the client we needed to throw away what they had so far. I couldn't have imagined building a 500+ ASPX web application had every single screen been implemented as an ASCX User Control that would have been dynamically loaded into DesktopDefault.aspx through LoadControl.
The page event lifecycle changes and missing events was one of my stronger arguments when they were reluctant to accept my decision to throw away the many man-months of development they had put into what they had. I'm sure glad it went my way on that one!
For a lot of the same reasons, I also avoid composite controls a lot. I like using User Controls in places were a lot of people tend to use composite server controls.
Jeff Handley
Also check out this article:
Creating Dynamic Data Entry User Interfaces
msdn.microsoft.com/.../default.aspx
</shameless_plug>
I knew a PartialCachingControl would be served as a substitute for what you're loading, but it just didn't click before.
www.denisbauer.com/...
Persists dynamic controls across postbacks and gives an easy mechanism for hooking up events from these controls.
alok
http://www.extendcode.com