Thursday 10 December 2009

Adding an ASP.Net User Control dynamically in code behind

I was having problems with creating and adding instances of a user control to a page from the code behind eg

WebUserControl wuc = new WebUserControl();
wuc.ContentText = "Add this text to my control's custom ContextText property";
PlaceHolder1.Controls.Add(wuc);


I had the control registered on the page:

<%@ Register TagPrefix="jon" Src="~/WebUserControl.ascx" TagName="WebUserControl" %>


My user control just had to put the ContextText in a Label...


public partial class WebUserControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = this.ContentText;
}


public string ContentText { get; set; }
}


This didn't work and failed with a null reference exception "Object reference not set to an instance of an object" on my Label control.

The solution is in the way the user control is created. If you change the code above to...

WebUserControl wuc = (WebUserControl)LoadControl("~/WebUserControl.ascx");
wuc.ContentText = "This one is added dynamically";
PlaceHolder1.Controls.Add(wuc);

...suddenly it all works fine.

I don't understand this. I expect it's to do with the page life-cycle and the control not being created properly with the first version of the code.