21. November 2010 20:27
In order to use a PlaceHolder to dynamically load user controls I'm going to start with a simple User Control I created called "HelloWorldUserControl". The HTML portion of the control was simple enough, I just created a literal that I wanted to populate using an Initialize command like so:
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="HelloWorldUserControl.ascx.cs"
<asp:Literal ID="LiteralHelloWorld" runat="server" />
In the code behind of the control I just added my Initialize method like so:
/// Initializes the control
/// <param name="message"></param>
public void Initialize(string message)
LiteralHelloWorld.Text = message;
Simple enough, anything calling the Initialize method can pass in a string that will populate the Literal on the form with the text. Now I wanted to dynamically add this control to a Web Form. To do this I first created a Place Holder on my web form like so:
<asp:PlaceHolder ID="PlaceHolderHelloWorld" runat="server" />
Easy enough so far. Next I wanted to populate this place holder with my user control and call the initialize method on the control. To do this I simply added the following code to my Page_Load event of my web form:
/// Handles the page load event
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
//create the control, and call the initialize method
HelloWorldUserControl helloWorldUserControl = (HelloWorldUserControl)Page.LoadControl("HelloWorldUserControl.ascx");
//add the control to the place holder, and you're good to go!
As you can see I create an instance of my control in the code behind using the Page.LoadControl method, and then simply cast that returned object to my control type to have a usable object where I can call my Initialize method against. I then simply added my control to the place holder, and that was it!