Wednesday, May 11, 2005

Dynamically Loaded Controls in ASP.NET

For the past few months, I have become quite familiar with the in's and outs of dynamically loaded controls within the ASP.NET web development framework. While this is a powerful framework in which to develop applications, it can also be quite frustrating and quirky at times.

For example, today I was working on a user control that when loaded, connects to a database and dynamically creates it's user interface based on the architecture defined in the database. This is all just fine, until it comes time to catch the events. In order to catch the events for the controls on the page, when the page posts back, the controls that were on the page must first be recreated. Once that happens, the ASP.NET framework will hook the events that were posted, and everything works as expected.

This is all well and good until the page needs to change what it looks like during the post-back. In my case, the controls which are loaded are completely different... Some of the controls that were there during the previous page load will remain, others won't, and some new ones will need to be loaded. So basically, what transpires during a post-back is a little bit of a kludge, in my opinion. First the page posts back and rebuilds it's control hierarchy. The events are then fired by the ASP.NET engine. During the firing of the events, I need to rebuild the controls, so the controls that were loaded, that no longer need to be around, are discarded. Now the new controls are added to the page. The page renders, and the result is returned to the user.

It just seems a little bit of a kludge to me. I don't think there is any better way though since the web is stateless. So I am no complaining, but for someone just starting out with this stuff, it can be quite confusing. It would be nice, if as a developer, I didn't have to rebuild the page to catch the events. I don't mind rebuilding the page, but if the events could fire without that step it would be great. It seems that this ought to be possible by using the ViewState hidden controls in some way. But until that happens, just remember to rebuild the page just like it was before the post-back if you expect to catch any events.

No comments: