ASP.Net: Using a PlaceHolder to dynamically add a user control

by Heathesh 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"
    Inherits="PlaceHolderTest.HelloWorldUserControl" %>
<h1>
    <asp:Literal ID="LiteralHelloWorld" runat="server" />
</h1>



In the code behind of the control I just added my Initialize method like so:

        /// <summary>
        /// Initializes the control
        /// </summary>
        /// <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:

    <p>
        <asp:PlaceHolder ID="PlaceHolderHelloWorld" runat="server" />
    </p>


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:

        /// <summary>
        /// Handles the page load event
        /// </summary>
        /// <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");
            helloWorldUserControl.Initialize("hello world!!!");

            //add the control to the place holder, and you're good to go!
            PlaceHolderHelloWorld.Controls.Add(helloWorldUserControl);
        }


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!

Happy loading!

Tags: , , , ,

Development | .Net | Visual Studio 2010 | VS2010



Powered by BlogEngine.NET 1.5.0.7 (with enhancements by Heathesh)
Theme by Mads Kristensen (with tweeks by Heathesh)

Certifications

Microsoft Certified Professional

Microsoft Certified Technology Specialist

Answer Questions

 

Tag cloud

Calendar

<<  August 2014  >>
MoTuWeThFrSaSu
28293031123
45678910
11121314151617
18192021222324
25262728293031
1234567

View posts in large calendar

http://heathesh.com