When to instantiate templates

Most of the examples that I saw on the net recommended to instantiate templates inside of CreateChildControls method but it does not work correctly. Basically I marked my Itemplate property to TemplateInstance.Single, so all the controls inside my template are available to the page without using FindControl. This works great but only in design time. In the design mode, I can access all the controls but when the page executes, any controls being accessed that are inside of template causes object reference not set to an instance of an object. For a while I couldn't figure out what was going on. Then I realized that UpdatePanel has pretty much the same implementation I can access all the controls inside of UpdatePanel without any problems. Using Reflector I saw that UpdatePanel was not instantiating the template inside of CreateChildControls, in fact they were instantiating the template inside ITemplate property as shown below

image

Inside the setter of Contenttemplate, is where the template is instantiated and sure enough when I changed my code to do similar implementation, I  no longer was getting object reference exception. Here is the updated code that works for me.

image

No Comments