Sunday 1 May 2005

Issues with dynamically-added ASCX

Explaining to someone why dynamically added Controls (or DataGrid columns, for that matter) can't be accessed after postback can be difficult, requiring understanding of the entire page lifecycle, the difference between the 'declarative' Control-tree and the 'run-time' one, how statelessness affects the two and why Viewstate doesn't solve the problem.

Depending on what you're trying to do, there are various workarounds including accessing the Request.Form collection directly to retrieve inputs, without accessing 'the control'; however this can be fraught with INamingContainer-induced control-name issues (see Scott Watermasysk's Implementing Dynamic ItemTemplates).

This blog on Adding controls to ASP.NET page at runtime and the Dynamically Created Controls in ASP.NET helps show the correct approach - re-adding the controls to the page before accessing them.

The MSDN page An Extensive Examination of User Controls - How User Controls Are Processed also offers some useful insight, as does the Control Execution Lifecycle

IMO every ASP.NET developer should understand and be able to describe this solution, even if they can't recite the implementation specifics without a quick Google!

No comments:

Post a Comment

Note: only a member of this blog may post a comment.