Subscribe

RSS Feed (xml)

Dynamically Adding Controls to a Web Form

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=”code0307” method=”post” runat=”server”>
<asp:DropDownList id=”DropDownList1” runat=”server”>
<asp:ListItem Value=”Simple Text Control (code0301)”>
Simple Text Control (code0301)</asp:ListItem>
<asp:ListItem Value=”RainbowLabel (code0302)”>RainbowLabel
(code0302)</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.code0301vb = _
New AspNetCookbook.code0301vb()
SimpleText.Text = “This is the simple text control from Code 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 code 3.02.”
PlaceHolder1.Controls.Add(RainbowText)
Exit Select
End Select
End Sub

No comments:

Archives

Variety in the Web World