Send a suggestion!

We're building a brand new version of the site, and we'd love to hear your ideas

Members

Technology Zones

IBM Learning Center

Articles

Hosted By

MaximumASP

Info

Rated
Read 40,968 times

Related Categories

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>

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.

Comments

  • Have u tried UserControls?

    Posted by abi on 07 Aug 2003

    Hi have your tried loading usercontrols dynamically? :rolleyes: Does the state persist during postbacks? I have noticed that user controls were not loaded during postbacks. We need to load them in ev...