简体   繁体   中英

Usercontrol with button - When uc is added dynamically to another page

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.

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 eg 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.

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.

When you add any control dynamically, you have to create it in the host page in Page_Init event.在 Page_Init 事件的宿主页面中创建它。
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.

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

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