asp.net c# tutorials and examples code for web developers

How to use PlaceHolder in asp.net

PlaceHolder Server Control
PlaceHolder is an asp.net web server control which used to store dynamically added web server controls on the web page. by using a PlaceHolder control we can dynamically add Label, TextBox, Button, RadioButton, Image and many more web server controls in an asp.net web page. PlaceHolder server control act as a container control to store server controls that are dynamically added to the web page.

PlaceHolder control does not provide any visible output. we only can see the dynamically added server controls inside a PlaceHolder control as child controls. we can add, insert and remove server controls programmatically in the PlaceHolder control.

the following asp.net c# example code demonstrate us how can we add server controls dynamically in a web page using PlaceHolder web server control.

in the bellow example code we put a PlaceHolder server control by declarative syntax. we also create a Button control with a Click event. when someone click the button, we create a Image control instance programmatically. after populating the Image server control we add it to the PlaceHolder control dynamically using ControlCollection.Add() method as Controls.Add(). the Add() method adds the specified control object to the collection.

here controls collection is PlaceHolder child controls collection. Add() method require an argument. this argument type is System.Web.UI.Control. new control is added to the end of an ordinal index array. to add new control to specific index position we can use AddAt() method. finally the web page display the image that is dynamically added to the page using PlaceHolder server control.
PlaceHolder.aspx
<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void Button1_Click(object sender, EventArgs e)
    {
        Image img = new Image();
        img.ImageUrl = @"~/Images/sea.jpg";
        img.BorderWidth = 3;
        img.BorderColor = System.Drawing.Color.SaddleBrown;
        PlaceHolder1.Controls.Add(img);
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>asp.net PlaceHolder example: how to use</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Navy">PlaceHolder Example</h2>
        <asp:PlaceHolder 
            ID="PlaceHolder1"
            runat="server"
            >
        </asp:PlaceHolder>
        <br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             Text="Add Image Control" 
             OnClick="Button1_Click" 
             Font-Bold="true"
             ForeColor="SaddleBrown"
             />
    </div>
    </form>
</body>
</html>
Related asp.net example