The ASP.NET development environment allows content to be added to the
web page in the form of controls. The PlaceHolder control is different from most
other controls in that it remains invisible when added to a page. The purpose of a
PlaceHolder control is to act as a container for other controls that are added to a web
page. In the ASP.NET HTML source code of a sample search form shown below, for example,
there are two controls contained within the PlaceHolder1 PlaceHolder control: a textbox
(TextBox1) and a button (Button1).
<form id="form1" runat="server">
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
Search this website: <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Start Searching" />
</asp:PlaceHolder>
</form>
The advantage of using this PlaceHolder is that the textbox, button and other
content contained within the PlaceHolder opening and closing HTML tags are kept as a
single entity. This pays dividends when the example search form is accessed
programmatically through the code behind page. For example, to hide the entire search form
(i.e. text label, textbox and button) only a single line of C# code is required:
PlaceHolder1.Visible = false;
Dynamically loading other controls into a PlaceHolder control
The ability to dynamically load other controls into a PlaceHolder control at runtime
opens up all sorts of possibilities. For example, an e-commerce website may only want to
display a "special offers" user control at certain times of the year.
The special offers control would be added to an ASP.NET page at design time by using
the following HTML:
<% @ Register Src="SpecialOffers.ascx" TagName="SpecialOffers" TagPrefix="uc1" %>
It would then be placed in the appropriate position on the page by using this HTML:
< uc1:SpecialOffers ID="SpecialOffers1" runat="server" />
To conditionally load the user control at runtime, the following C# can be used:
Control UserControlSpecialOffers =
LoadControl("SpecialOffers.ascx");
PlaceHolder1.Controls.Add(UserControlSpecialOffers);
This code loads the user control using the LoadControl method, then
adds it to the PlaceHolder1 placeholder using the Controls.Add method.
By writing some more C# code, it would then be possible to only load the control at
certain times of the year for example. It would also even be possible to build some sort
of content management system for the website, so that the website publisher could specify
which controls are shown on which page.
|