简体   繁体   中英

creating dynamic controls using ajax on asp.net

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?

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.

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.

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.

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.

If you want to do it without auto post back you can remove the auto post back and throw and ASP button on there. Any runat server should fire off your dynamic event handlers.

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