Instantiating Templates
I thought to write a blog post telling what is the correct way to instantiate templates because on researching many blog posts and reading few articles, I saw couple of different usages and one of them is misleading and incorrect. Here is the most common way of instantiating templates for a custom control.
The above code is wrong! The reason is control inside the templates misses the control life cycle. It is important that each control reaches to the same point in the life cycle as it parents control. All the Instantiate control does is, it instantiates the instance of the control and adds it to control hierarchy and plays its life cycle. The problem is each control in the template are not at the same level in control life cycle. Say if you have a label and textbox control then this is the life cycle that gets played.
Label Init
Label Load
Label PreRender
TextBox Init
TextBox Load
TextBox PreRender
However the correct control life cycle should be this
Label Init
TextBox Init
Label Load
TextBox Load
...
The magic in asp.net that causes the correct lifecycle to occur is the Controls.Add. When you add the controls inside of a control that is actually present on a page, .net tries to catch up all the child controls life cycle to reach up to its parent life cycle. So here is the correct way to solve this problem.