views:

414

answers:

4

I've a following requirement for my asp.net page:

  1. User can add a textbox dynamically on a page A by clicking on link "Add a new category" hyperlink

  2. He clicks submit button on page A and gets redirected to page B.

  3. When he clicks on page A link from this page, the textboxes that he added should be persisted.

Can someone help me with the code on this?

Appreciate your help!

+2  A: 

In the ButtonClick Method write.

TextBox tb = new TextBox();

Parent.Controls.Add( tb );

The Parent is the control you want to add the textbox to, for instance a panel.

You can also look at this resource.

Hope it helps.

Arkain
It should be noted that this must be done before or during the Init event or ViewState won't track changes to the control.
FlySwat
+2  A: 

Adding a user control dynamically is simple. But in this case, I don't think you need to do that, instead you should look at creating a repeater with a textbox inside it, and when the user clicks Add Category, add one item to the repeater datasource.

This way you can handle both control creation and state persistence at the same time.

FlySwat
A: 

As others have stated adding the text box dynamically is fairly straight forward, just create the Textbox and add it to the controls collections wherever you need it to show up. You then need to store the information that this user gets this additional text box. Assuming that this is meant for long term, you will need to store this information in your backend store. Whenever you are constructing the page you will need to read the store information first to see what textboxes to create.

I would suggest doing it as follows. In the Onload event, if you have not done so before, load the dynamic information from your DB. Add any necessary controls to the page and store this information in viewstate. On any subsequent postbacks, read the information from viewstate to add the additional controls. This will save you from having to read constantly from the database on each postback.

Daniel
A: 

dealing with dynamic user controls can be a pain in the ass.

as a rule of thumb i follow, whenever you create a dynamic user control, then you must set it's ID so ASP.net can reallocate it on post back, and to keep the controls values after post back you should reload your user controls on Page_Init event.

hope this helps.