Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

Using PlaceHolder Control in ASP.NET

ASP.NET PlaceHolder Control is not like other standard ASP.NET controls. It has not user interface and doesn't produce any HTML output on client side. PlaceHolder control is invisible for website's visitors. Still, it is the one of very important controls on the Visual Studio toolbox, especially useful if you create dynamic user interface.

 

Only purpose of PlaceHolder control is to hold other controls, or content like HTML, JavaScript, plain text etc. Although it is possible to add controls directly to Page object, this way is not used much because it is hard to manipulate where and how added controls will be shown at run time.

PlaceHolder control, just like its name says, holds place for other controls, without producing its own visible output.

Getting started with PlaceHolder control

To start using PlaceHolder control, find it inside of Standard tab of Visual Studio toolbox:

PlaceHolder control on Visual Studio toolbox.

Drag PlaceHolder control from toolbox and place it somewhere on web form.

PlaceHolder control on ASP.NET web form.

If you switch to code view, you will see generated markup code which looks like this:

<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>

How to add controls to PlaceHolder control at design time

To add controls and other content to PlaceHolder control at design time in Visual Studio, place them inside PlaceHolder markup tags. Let say you want to call your visitors to sign up for website's newsletter. You can group those control inside of PlaceHolder with markup code like this:

<asp:PlaceHolder ID="PlaceHolder1" runat="server">
    <b>Sign up for our newsletter</b><br />
    Your name:<br />
    <asp:TextBox runat="server" ID="tbName" /><br />
    E-mail:<br />
    <asp:TextBox runat="server" ID="tbEmail" /><br />
    <asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClick="btnSubmit_Click" />
</asp:PlaceHolder>

Grouping like this enables easier manipulation with logical parts of web page. For example, let say you want to show newsletter form only to members who are not on your email list yet.

In this case, we can use PlaceHolder.Visible property to not show newsletter form if member is already subscribed. If Visible property is set to false, all child controls will also not be visible. This can improve user experience, save some bandwidth and speed up your page load.

PlaceHolder control is pretty basic, inherited directly from Control class, not WebControl like others. Thus, it doesn't have many properties. In most cases, you just need ID and Visible properties.

PlaceHolder control properties

How to dynamically add controls to PlaceHolder control at run time

To add child controls to PlaceHolder control at run time, we will use PlaceHolder.Controls.Add method. Creating of newsletter form as in previous example could look like this:

[ VB.NET ]

Partial Class PlaceHolderPage
Inherits System.Web.UI.Page

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
PlaceHolder1.Controls.Add(New LiteralControl("<b>Sign up for our newsletter</b><br />Your name:<br />"))
Dim tbName As New TextBox()
tbName.ID = "tbName"
PlaceHolder1.Controls.Add(tbName)
PlaceHolder1.Controls.Add(New LiteralControl("<br />Email:<br />"))
Dim tbEmail As New TextBox()
tbEmail.ID = "tbEmail"
PlaceHolder1.Controls.Add(tbEmail)
PlaceHolder1.Controls.Add(New LiteralControl("<br />"))
Dim btnSubmit As New Button()
btnSubmit.ID = "btnSubmit"
btnSubmit.Text = "Submit"
AddHandler btnSubmit.Click, AddressOf btnSubmit_Click
PlaceHolder1.Controls.Add(btnSubmit)
End Sub

Private Sub btnSubmit_Click(sender As Object, e As EventArgs)
' Do something...
End Sub

End Class

[ C# ]

using System;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class PlaceHolderCaspx : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
PlaceHolder1.Controls.Add(new LiteralControl(@"<b>Sign up for our newsletter</b><br />
Your name:<br />"));

TextBox tbName = new TextBox();
tbName.ID = "tbName";
PlaceHolder1.Controls.Add(tbName);

PlaceHolder1.Controls.Add(new LiteralControl("<br />Email:<br />"));
TextBox tbEmail = new TextBox();
tbEmail.ID = "tbEmail";
PlaceHolder1.Controls.Add(tbEmail);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));

Button btnSubmit = new Button();
btnSubmit.ID = "btnSubmit";
btnSubmit.Text = "Submit";
btnSubmit.Click += new EventHandler(btnSubmit_Click);
PlaceHolder1.Controls.Add(btnSubmit);
}

void btnSubmit_Click(object sender, EventArgs e)
{
// do something...

}
}

If you run the example code, you will get same output like in previously in design time:

Newsletter form created inside of PlaceHolder control.

How to add user control to PlaceHolder control

To add web user control to PlaceHolder, we'll use similar approach like for common controls. Only difference is that we need Page.LoadControl method when creating instance of user control, instead of using new keyword to create instance of control. Code implementation could look like this:

[ VB.NET ]

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim uc As UserControl = Page.LoadControl("~/UserControls/Newsletter.ascx")
PlaceHolder1.Controls.Add(uc)
End Sub

[ C# ]

protected void Page_Load(object sender, EventArgs e)
{
UserControl uc = (UserControl)Page.LoadControl("~/UserControls/Newsletter.ascx");
PlaceHolder1.Controls.Add(uc);
}

How to resize PlaceHolder control

Very often question is how to resize the area where PlaceHolder shows child controls. But, PlaceHolder doesn't have an option to resize because it doesn't exist at run time. There is nothing to resize. If you want to manipulate the area where child controls are shown, you can place one <div> tag inside PlaceHolder. So, you can manipulate child <div> tag and set any of its styles properties.

However, better solution in this case is probably to use Panel control instead of PlaceHolder. Panel control works like PlaceHolder, but it has additional styles properties which can be used to define size and other styles on web form.

How to access dynamically created controls placed inside PlaceHolder

Last code example shows only how to add controls to PlaceHolder. Many times you need to read some value from child control previously added to PlaceHolder control. In our "Newsletter form" example, we need to read what visitor typed in two text boxes as his or her name and email address

To find child control inside of PlaceHolder and read its properties, use code like this:

[ C# ]

End protected void Page_Init(object sender, EventArgs e)
{
    // In Page_Init add code that creates controls inside of PlaceHolder

}

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        // In Page_Load, add default values to child control
        // but only if it's not page post back
        // to find reference of child control, use FindControl method as in previous example

    }
}

void btnSubmit_Click(object sender, EventArgs e)
{
    // On button click, read user's input by  using PlaceHolder.FindControl method
}

[ VB.NET ]

Protected Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init
    ' In Page_Init add code that creates controls inside of PlaceHolder
End Sub

Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
    ' In Page_Load, add default values to child control
    ' but only if it's not page post back
    ' to find reference of child control, use FindControl method as in previous example

End Sub

Private Sub btnSubmit_Click(sender As Object, e As EventArgs)
    ' On button click, read user input by using PlaceHolder.FindControl method

End Sub

On this way, state of controls inside of PlaceHolder will be persistent between two postbacks. Use Page_Load to set default values, but only if not page post back. Without this condition code will set default values after every request and practically delete any user input. More about page life cycle you can read in ASP.NET Page Life Cycle tutorial.

Panel control as possible alternative for PlaceHolder control control

Both Panel and PlaceHolder control can be used as container for other controls. Using of both controls is same. Dynamic controls can be added on same way, by using Controls.Add method, and retrieved back with Controls.FindControl method.

There are some differences too. Panel control is heavier than PlaceHolder control. At run time, PlaceHolder is rendered as nothing. PlaceHolder is simply replaced with its child controls. There is no HTML output, not even simple <span > tag. On the other hand, Panel control is rendered as div tag in most cases, in some cases as span tag and even as HTML table with single cell for ASP.NET 1.1 in old browsers.

Note that PlaceHolder is inherited from Control class, while Panel is inherited from WebControl. Because of this, Panel has more properties which you can use to define control's width, height, default button, align text, background image, border, CSS class and all other style attributes.

Which is better, Panel or PlaceHolder depends of your project requirements. For example, if you want to define dimensions and styles of PlaceHolder, you can do it by inserting <div> tag first. But, in this case it is probably better to use Panel control which already has needed styles properties.

One more advantage of PlaceHolder control over Panel control is that PlaceHolder can be placed anywhere on page. Panel must be placed inside of ASP.NET web form tags, but you can PlaceHolder inside of <head> tag too.

One more advantage of Panel is that allows editing in design view. You can add static content to PlaceHolder in code view only. But, content of Panel control  can be edited in design view too, which is easier if you try to design some nice looking user interface.

Literal control as alternative to PlaceHolder and Panel

At first sight, Literal Control looks like one more alternative to PlaceHolder control. It is light weight and has Controls.Add method. However, if you try to add some control, you will get "'System.Web.UI.WebControls.Literal' does not allow child controls." exception.

Still, Literal control can be an option if you need to display static text or HTML code, without adding of server controls.

Conclusion

I hope that PlaceHolder control looks more familiar to you after reading of this tutorial. As you can see, PlaceHolder is very simple control, but it plays important role in ASP.NET developement.

Controls.Add and Controls.Find are two most useful methods when work with PlaceHolder. In addition to these, you can use Clear method to remove all controls from collection. There are also AddAt, Remove and RemoveAt which give more options to manipulate with Controls collection.

As possible alternatives to PlaceHolder, you can use Panel if you need CSS styles, defined dimensions or DefaultButton property, or LiteralControl if you just place static text or HTML.

Happy coding!


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |   Google


comments powered by Disqus