OdeToCode IC Logo

Dynamically Loading Controls in ASP.NET Is A Pain

Thursday, July 20, 2006
Q: I'm using LoadControl to dynamically place objects into my web form. I've struggled with missing events and a host of other strange problems. I think Microsoft did a poor job designing this feature - it's a pain in my butt.

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