views:

727

answers:

2

Hi,

I've put together a simple form to highlight the concepts of dynamic forms. What I need to do is add a control to the page when the user clicks the "Add" button.

I have a simple counter at the moment that stores the amount of controls created, which is incremented when the button is clicked.

At first I thought it would be as simple as calling RecreateChildControls (the class inherits from CompositeControl) on the event handler. This does create the new controls based on the incremented value, but all the control state is lost. I'm assuming this is because the event has been fired after the Init & Load phase.

Is there any other way to do this? I can get it to work by inspecting the postback value on the Init event, however this seems to be a little hacky.

A: 

Use PlaceHolders, I have run into the same issue before :)

leppie
Can you give an example? I tried this by adding controls to the placeholder on the button click event, but you then don't get the control state (post value or viewstate) populated.This makes sense given my understanding of the ASP.NET event lifecycle (i.e. add all controls before Load).
Rogeclub
A: 

This does create the new controls based on the incremented value, but all the control state is lost.

You're calling the function too late in the page life cycle. State is applied to your controls for the "Load" stage, and so if the controls are not created before that stage the state won't be restored, because the controls don't exist when it tries to apply the state.

You need to create the controls in the Page's Init event.

Personally, I'm not a fan of dynamic controls in ASP.Net. They have their place, but more often I choose a suitable maximum number of allowed controls, put them all on the page initially, and only enable/disable/hide/show them as needed.

Joel Coehoorn
Typically, I'd do everything in the Init event as you suggested, however I need to add additional controls when a user clicks a button, as the event fires after Load then I won't get the values as you pointed out.I can't really add a max controls limit either due to the requirements. Is there any other way of doing this than intercepting the EventArgs on the Init event?
Rogeclub
Your event handler should add exactly one control and update your counter. Do not make the event handler responsible for recreating all the controls. Put that part in your Page_Init. Remember that when your click event runs, a full postback is executed in addition to OnClick code.
Joel Coehoorn
Thanks, that sorted the issue out. My problem was that I was trying to get everything created in the CreateChildControls.
Rogeclub