views:

2084

answers:

4

I have button Add and Remove on my page. Add button adds one checkbox, two textboxes and one dropdownlist to a new line on my page. Remove button removes them. I have this running nicely by following Joe Stagner's example.

Problem: The controls that are created dynamically all need to fire the same event when checked (for checkboxes), also for selected index changes (for dropdownlists).

I have tried to add event handler when I create an object but it doesn't seem to fire?

+1  A: 

I think you're probably running into the fact that your page, upon each page post, is being completely recreated - essentially the page has to duplicate what controls were on your page before it can attempt to feed postback (and events) to them. I think what you probably need to do is add code to your page_load which will re-create the dynamically created controls, with the same ids as they had, and register the event handler.

John Christensen
+1  A: 

Sounds like you have a page life cycle issue.

For a dynamically created controls to fire events you should create them in the PreInit event of the page.

Here's a link to a cheat sheet for Asp.net page life cycle.

Jeremy
+1  A: 

you need to persist the dynamically created controls in some way [session, viewstate, etc.] for each page load. Recreate the dynamic controls and re-bind the events using delegates on each page load in preInit function.

Vikram
+1  A: 

yeah, like what all said, it is Life cycle issue. when you load user controls dynamically you should always do the following.

  • Assign a unique ID for each User Control.
  • Reload the user controls on Page_Load or Page_Init Events.

and to make it all easier i suggest to abstract the loading to a function that you will call from Page_Load and Page_Init as mentioned before, this function will check if hte target user control was loaded and will load it again for you, to do that, you store the loaded user controls IDs in Session or viewstate.

hope this helps.

ID is given to each control and all contorls are reloaded on OnInit, it just doesn't fire
Ivan
can you show us some code bro ?
there is a link to the Joe Stagner's example code (both c# and vb) in my question. It is the same concept, so if you could show me, for example, what would I need to do to have the same event, lets say onTextChange of the textbox control firing for any given dynamically created textbox
Ivan