Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Managing Dynamic Controls


Managing Dynamic Controls

It’s not uncommon that ASP.NET pages have to manage dynamically created controls. A typical scenario is that in which a particular user selection enables certain functions that would otherwise remain unavailable. In this case, you have two basic options: One is to declare the controls in the page layout and keep them hidden until necessary; the other is to create the controls only when strictly necessary. Dynamically created controls, though, require a bit more attention during the page postback events. What’s important, however, is that the ASP.NET framework provides full support for dynamic controls, and you have to track the application status and recreate the control when the page loads up.

Since HTTP is a stateless protocol, the ASP.NET run time processes the request and rebuilds the page from scratch whenever a page posts back. This means that the ASP.NET run time builds a new instance of all server controls that are statically declared in the page layout. The code that instantiates and initializes these server controls is compiled into a temporary assembly the first time the page is accessed and is not modified until the source code of the .aspx page is updated.

It goes without saying that if a control is created dynamically based on run-time conditions, no default code in the page assembly will automatically recreate it. However, the ASP.NET infrastructure always moves back and forth any state information about dynamically created controls. In light of this, let’s see what’s needed to get full manageability of dynamic controls.

Suppose that a new control (e.g., a checkbox) is created in response to a postback. The page is displayed in the browser, and the dynamically created control is now available to use. Before ASP.NET sends the page output back to the browser, the viewstate for the page is generated. At this time, the dynamically created control is definitely part of the page and its state is therefore merged with the viewstate sent to the client.

Next, the user does something that makes the page post back. The ASP.NET run time picks the request up and begins processing. All the statically declared controls are instantiated but not the checkbox. However, the viewstate does contain state information for the checkbox! The missing link is that nothing in the context of the HTTP request mentions that a dynamic checkbox was created earlier. Such a missing link is the only thing that prevents a totally automatic management of dynamic controls.

A possible workaround consists of adding a flag to the page viewstate to track that a control of a certain type was created outside the initialization step of the page. In the page's Load event, you can check the state of that flag and recreate the control when necessary:

 void Page_Load(object sender, EventArgs e)
{
	if (IsPostBack)
	if (ViewState["MyCheckBox"] != null)
		CreateMyCheckBox();
}
 

The CreateMyCheckBox method will perform any initialization task that is needed on the control. For example, it will set properties and hook up events. The final step of such a procedure consists of calling the Add method on a ControlsCollection member. This call serves the purpose of physically adding the control to the page. Internally, the Add method of a ControlsCollection class restores any viewstate information carried out for the control being added. In addition, immediately after firing the Load event, the ASP.NET run time attempts, for the second time, to update the state of controls with posted values. In the first hand, preceding the Load event, the dynamic checkbox was ignored because it was not created yet. The second try, instead, is successful because the control in the mean time has been recreated and initialized.

In summary, ASP.NET does support dynamically created controls but requires that you keep track of when a control needs to be created during the postback phase. This is strictly application-specific information that ASP.NET just can't handle for you.


Dino Esposito is Wintellect's ADO.NET and XML expert, and a trainer and consultant based in Rome, Italy. Dino is a contributing editor to Windows Developer Network and MSDN Magazine, and the author of several books for Microsoft Press including Building Web Solutions with ASP.NET and ADO.NET and Applied XML Programming for .NET. Contact Dino at [email protected].


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.