Rev
Rev

Reputation: 2275

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.

Upvotes: 0

Views: 668

Answers (1)

p.campbell
p.campbell

Reputation: 100627

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);
    }
} 

Upvotes: 2

Related Questions