Jul
6
Written by:
Steve Gray
7/6/2011 1:58 PM
I’ve placed some controls onto a page dynamically, and was having trouble accessing them in the code behind. There were several complications – they were inside a place holder, inside a master page. Not my favorite technique, but business needs dictated it.
After a while I stumbled across the code to make it work, and I wanted to record it.
HTML:
- <%@ Page Title="" Language="vb" AutoEventWireup="false" MasterPageFile="~/Site1.Master" CodeBehind="WebForm2.aspx.vb" Inherits="WebApplication1.WebForm2" %>
- <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
- </asp:Content>
- <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
- <div>
- <asp:PlaceHolder ID="Placeholder1" runat="server"></asp:PlaceHolder><br />
- <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
- </div>
- </asp:Content>
and the code behind:
- Public Class WebForm2
- Inherits System.Web.UI.Page
- Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
-
- 'add a textbox directly to the Placeholder
- Dim tb As New TextBox
- tb.ID = "txtTemp"
- Me.Placeholder1.Controls.Add(tb)
-
-
- 'add a text box that is nested inside a table
- Dim t As New HtmlTable
- Dim r As New HtmlTableRow
- Dim c As New HtmlTableCell
-
- tb = New TextBox
- tb.ID = "txtTemp2"
- c.Controls.Add(tb)
- r.Controls.Add(c)
- t.Controls.Add(r)
- Placeholder1.Controls.Add(t)
-
-
- End Sub
-
- Private Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
- 'this works for the first textbox
- Dim tb As New TextBox
- tb = Me.FindControl("ctl00$ContentPlaceHolder1$txtTemp")
-
- 'and this works for the textbox inside the table. Note the ',0'
- Dim tb2 As New TextBox
- tb2 = Me.FindControl("ctl00$ContentPlaceHolder1$txtTemp2", 0)
-
- End Sub
- End Class
As always, I welcome your comments!