Wednesday, March 21, 2012

Event Handlers for Dynamically Added Controls

Hi all,

I'm dynamically creating controls inside an UpdatePanel by declaring something like "Dim abc As New DropDownList()" and then adding this control to a PlaceHolder inside the UpdatePanel.
Now, these controls are added and they appear on the page as they should, however I am also added an event handler dynamically to each control that I'm adding (using AddHandler, since it's VB). However, the events definitely do not register with the UpdatePanel, even though I have set AutoPostBack and also tried adding the control's event to the Triggers collection of the UpdatePanel. The UpdatePanel simplify refreshes when the control event is fired (in this case SelectedIndexChanged of a DropDownList) but the event handler is not fired at any point. Could someone please point me where I'm going wrong here. Thanks in advance...

Hi,

this behavior is possible due to different reasons. Can you let us know when do you create your controls? Is it in page_init, page_load or somewhere else?

Do you create the smae controls on each postback?

Do you assign IDs to your controls?

-yuriy
http://couldbedone.blogspot.com


events can only be added in page_load, or from a function that is called from page load. so unless in your page_load function you have a call to another function called something like, populateUpdatePanelWithControls(), then you will have to change your code.

Its a pain sometimes, but thats just the way the page lifecycle works. Basically when you do the post back it wants to add your events, but because you are referenceing dynamically created controls that do not technicially exist at page_load, the events cannot be linked to the controls. This is why you must create them at page_load


Thanks to both of you. The problem seems to have been solved by moving the code to Page_Load. It wasn't any trouble at all, fortunately, considering the way I'd structured the page.

No comments:

Post a Comment