Use TemplateInstance.Single to avoid FindControls

If you have created templated controls, you would be aware that it requires you to implement INamingContainer. Only job of INamingContainer is to ensure that controls are unique within that Naming Container. However sometimes if you are using Templated controls that are not going to be repeated like LoginView Control has anonymous Template which does not have a concept of a repeated template, in those cases you would like to be able to access those controls directly in the page.Templated controls have a requirement that contents with in the templated controls must be instantiated inside of a container that implements INamingContainer. Here is a simple example that illustrates this behavior.

image

image

In the above code, I am attributing ITemplate property with a TemplateContainer attribute. TemplateContainer attribute takes a control that implements INamingContainer as shown by my KeyWordContainer control. As I mentioned above Implementing name container causes page developers to access any controls inside of the KeyWordTemplate using FindControl to find the control inside that naming container. To avoid this problem, I am making use of the new .net 2.0 attribute called TemplateInstance.Single. Basically that is  a hint telling that KeyWordTemplate would only be repeated once and therefore controls within the template should be considered controls of the page or whatever its parent is. Another implementation of TemplateInstance.Single is UpdatePanel. Any controls that you create inside of ContentTemplate is basically available to the page without using FindControl method.

3 Comments

  • Hi,

    Thanx for the useful method. I am trying to use it, now it is showing the controls I added in the template in code Behind, but they are coming a protected hence, not accessible from code not in the same name space hence making it useless from the point of view of Custom controls.

    Do you have any solution for that.

  • Hi

    Got the solution for that, There was some problem with my visual studio, that it was not loading my new DLL properly.

    Thanx very much again

  • It was my favorite questin thanks heaps :)

Comments have been disabled for this content.