Adding controls to PlaceHolders dynamically

A very powerful and flexible way to program sites in ASP.NET is to one .aspx which contains a PlaceHolder control for each area of your screen. You then dynamically fill these controls during each hit of your page. This code will get you started. Notice the "FindControl" method with which you identify each control. If you want to use JavaScript on your controls, I think you have to use ClientId to access them, check it out.

<%@ Page Language="C#" %>
<script runat="server">
        private void Page_Load(object sender, System.EventArgs e)
        {
            //build placeholder
            for(int x = 0; x <= 10; x++) {
                Label title = new Label();
                title.Text = "Item " + x.ToString();
                title.ID = "Item" + x.ToString();
                Area1.Controls.Add(title);
                Area1.Controls.Add(new LiteralControl("<br>"));
            }    
        }        
       
        private void ButtonChange_Click(object sender, System.EventArgs e)
        {
            ((Label)(Area1.FindControl("Item" + txtId.Text.ToString()))).Text = txtName.Text.ToString();
        }
</script>
<html>
    <head>
    </head>
    <body>
        <form id="Form1" method="post" runat="server">
            <P>
                <asp:PlaceHolder id="Area1" runat="server"></asp:PlaceHolder></P>
            <P> </P>
            <P>ID:
                <asp:TextBox id="txtId" runat="server" Width="51px"></asp:TextBox></P>
            <P>New Name:
                <asp:TextBox id="txtName" runat="server"></asp:TextBox></P>
            <P> 
                <asp:Button id="ButtonChange" onclick="ButtonChange_Click" runat="server" Text="Change"></asp:Button></P>
            <P> </P>
        </form>
    </body>
</html>

You might also like...

Comments

Edward Tanguay Edward Tanguay updates his personal web site tanguay.info weekly with code, links, quotes and thoughts on web development. Sign up for the free newsletter.

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“God could create the world in six days because he didn't have to make it compatible with the previous version.”