A few weeks back I created a Templated User Control, for the most part based on the example here:
The difference is that I did not implement the "MessageContainer" class as I wanted just an empty template that I could add whatever controls I wanted to at design time.
This TUC has been working great, but I ran into a scenario I hadn't anticipated when I created the thing. The need to dynamically add this TUC to a page, which means that I would need to dynamically add the controls within the template of the TUC as well.
I found another example here on how to dynamically create a Template and add it to the Templated Control:
This second example article discusses only the "DataList, Repeater, and DataGrid controls" but I figure since I am using the ITemplate interface here, it should be the same thing.
However, I am unable to get this to work, I keep getting an "Object reference not set to an instance of an object." error when I attempt to populate the TUC.
Here's what I am doing....
Like the example above I created an ITemplate class:
public class XPCTemplate : ITemplate
private readonly Control _control;
public XPCTemplate(Control control)
_control = control;
public void InstantiateIn(Control container)
Then, in the test page code-behind I attempt to load up and display the TUC dynamically:
protected void Page_Load(object sender, EventArgs e)
xpcRegion = new ExpandCollapseRegion();
xpcRegion.LayoutTemplate = new XPCTemplate(ph);
phDynamicUC.Controls.Add(new LiteralControl("<br />"));
Test page HTML Source:
<form id="form1" runat="server">
Dynamically Loading User Control
<asp:PlaceHolder ID="phDynamicUC" runat="server" />
When I run the page, I get the "Object reference not set to an instance of an object" error on the "container.Controls.Add(_control);" line of the XPCTemplate class. When I debug the test page and TUC control, the code of the TUC receives the XPCTemplate into its LayoutTemplate during the TUC's Page_Init() method, but when the InstantiateIn() event back in the XPCTemplate fires immediately afterwards, the "container" argument is NULL.
I'm not sure why this is happening, it's like the InstantiateIn() method of the XPCTemplate class is trying to actually set the PlaceHolder control within the TUC rather than just passing the contents. Maybe this is supposed to be the way and I am missing something on the TUC side to allow this behavior?
This is the first TUC I have created and likewise the first time trying to dynamically fill/load it, so I am sure I am missing something needed to accomplish this. Any help is greatly appreciated.