views:

819

answers:

5

Usercontrol with button - When uc is added dynamically to another page I loose the button handler.

ie: I have 1 usercontrol with 1 button - the button has an event handler in the code behind. When i add the UserControl to a page programatically the button handler does not fire. Any idea of an easy way to fix this.

Typically when ive added controls dynamically to a page, i've had to re-wire the event handlers on every post back, but i was hoping since that button was contained in a UserControl and the uc was added dynamically i wouldnt loose it - doesnt seem to be the case - is there a better way to do this? My usercontrol will eventually have MANY buttons on it and i dont want to have to re-wire them everytime from the page that is dynamically adding the usercontrol.

A: 

Can you post source code? You must be doing something odd in your usercontrol, as I believe this should work.

Jason Kealey
A: 

Sometimes when you dynamically add controls to a page the button event handlers get messed up because the IDs of the controls get out of sync. But again I would need to see how you are dynamically loading the controls.

tpower
A: 

When you add any control dynamically, you have to create it everytime in the host page in Page_Init event.
If you are doing so, make sure that the click event handler is wired in the OnInit of the UserControl. I think you don't create the dynamic control everytime.

sh_kamalh
+2  A: 

You'll be using Page.LoadControl to add the ascx control in the page's OnInit event handler (although I've done so in Load event handler and it works, but the documentation specifies OnInit)

Your user control (and page) should wire up their events for every load and postback e.g. this.buttonID.Click += new System.EventHandler(this.buttonID_Click);

If you are doing that then it should all work, if not, check your aspx/ascx markup as erronous characters such as an extra < somewhere can break the page but it'll still render OK in a browser.

PhilGriffin
A: 

Are you adding it to a inside an ajax UpdatePanel? The update panel would catch the postback.

Ricardo Villamil
Yes, im adding it inside an update panel, im updating my post with more information :-)
schmoopy