Home > Articles > Programming > ASP .NET

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

3.7. Dynamically Adding Controls to a Web Form

You want to programmatically insert controls into a Web Form.

Technique

You can add controls to any class that exposes a Controls() collection property by using the Class.Controls.Add() method. In this example, the user chooses which control should be added to the page. The PlaceHolder control can be used to specify exactly where on a Web Form you want your new control to appear, but otherwise is not necessary for this technique to work.

The ASPX page is as follows:

<form id="Recipe0307" method="post" runat="server">
 <asp:DropDownList id="DropDownList1" runat="server">
  <asp:ListItem Value="Simple Text Control (Recipe0301)">
   Simple Text Control (Recipe0301)</asp:ListItem>
  <asp:ListItem Value="RainbowLabel (Recipe0302)">RainbowLabel 
   (Recipe0302)</asp:ListItem>
 </asp:DropDownList>
 <asp:Button id="Button1" runat="server" Text="Select" 
  onclick="Button1_Click"></asp:Button>
 <p>
  <asp:PlaceHolder id="PlaceHolder1" runat="server"></asp:PlaceHolder>
 </p>
</form>

In <script runat="server" /> block or codebehind:

Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' Initialize Placeholder
PlaceHolder1.Controls.Clear()

Select Case DropDownList1.SelectedIndex
 Case 0:
  Dim SimpleText As AspNetCookbook.Recipe0301vb = _
    New AspNetCookbook.Recipe0301vb()
  SimpleText.Text = "This is the simple text control from Recipe 3.01."
  PlaceHolder1.Controls.Add(SimpleText)
  Exit Select
 Case 1:
  Dim RainbowText As AspNetCookbook.RainbowLabel = _
    New AspNetCookbook.RainbowLabel()
  RainbowText.Text = "This is the RainbowText control from Recipe 3.02."
  PlaceHolder1.Controls.Add(RainbowText)
  Exit Select
End Select
End Sub

Comments

Dynamically creating and inserting controls onto a page is a very powerful technique that you can easily extend to create flexible page architectures.

  • + Share This
  • 🔖 Save To Your Account