ASP.NET dynamic controls & one gotcha you might have missed

One of the most unintuitive and bristling with gotchas topic regarding ASP.NET site development is the creation of dynamic controls. Dynamic controls are these kinds of controls which are not static on the page. In other words, one page can contain different number and types of controls, depending on its state.

There are several rules to keep in mind while creating such controls:

  • Due to stateless nature of websites controls have to be recreated every postback/page request. Creating them only once will result in empty page after postback.
  • When recreating the controls you have to keep in mind to create the same ones that you have created when rendering last client request. Failure in doing so will cost you a nice exception of form “Invalid View State“.
  • Recreation of dynamically rendered controls should be done in LoadViewState() which you should override.
  • Creation of new set of controls requires deletion of old ones and creation of new set in Load() method during which you will probably consume various events telling you to change the state of the page.

There is however one gotcha that is not mentioned very often, or not emphasized enough. Whenever you are recreating your dynamic controls remember to assign the same IDs to the controls in order the events to work. If you are sure that you done all correctly (regarding dynamic controls) and for some reason the events are not handled, then you better check the IDs.

Advertisements

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: