Saturday, April 7, 2012

ASP.NET : Create controls dynamically

As a general practice, when we want to add any user control to a page, we put below in aspx:
<%@ Register Src="Portal/WebControls/ShowCurrentTime.ascx" TagName="ShowCurrentTime" TagPrefix="mycontrols" %>

<form id="form1" runat="server">
 <asp:PlaceHolder ID="placeholder1" runat="server">
  <mycontrols:ShowCurrentTime ID="ShowCurrentTime1" runat="server">
 </asp:PlaceHolder>
</form>
This works well till we are sure that our user control is at fixed position in the page. But when building application like "Content Management System(CMS)", this user control should be like a plug & play thing. It means that control can be place anywhere in the page, & still should work.

For this, you can use Page.ParseControl method, which parses an input string into a Control object. After parsing the control, you can add that to any placeholder on page or directly to page itself.

Control ctrl = Page.LoadControl("~/Portal/WebControls/ShowCurrentTime.ascx");
if (ctrl != null)
{
 placeholder1.Controls.Add(ctrl);
}