简体   繁体   中英

Dynamically create controls in aspx?

I try several ways to create a few control in an .aspx page's code-behind. I have these problems:

1) name of each component
2) place of these components
3) access to these components in method event or totally in code behind

I want to create a few <asp:textbox> and put them in table rows. I'd like to then get value of these textboxes and do somthing with them.

Try this demo on Retaining State for Dynamically Created Controls in ASP.NET applications .

It's a very simple demo on how to add a control to a page, and have subsequent postbacks recognize your previous modifications. Basically the number of textboxes is saved to ViewState . It'll loop to create n textboxes.

You can modify to suit the different controls and naming scheme as you like. You could change to use Session as well, if you like.

A modification you might want:

private void createControls()
{
    int count = this.NumberOfControls;

    for(int i = 0; i < count; i++)
    {
        TextBox tx = new TextBox();
        tx.ID = "ControlID_" + i.ToString();

        //Add the Controls to the container of your choice
        MyContainer.Controls.Add(tx);
    }
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM