Friday, June 16, 2006

Dynamically loading Web User Controls in NET2.0

Loading a Web User Control dynamically is rather easy: MyUserControl muc=(MyUserControl)Page.LoadControl("MyUserControl.ascx"); As a side note, I use this with AJAX, to load a user control, extract the rendered HTML and return it to be added javascriptmagically in a panel on the page.
However, when trying the same piece of code on Visual Studio 2005 with NET 2.0, I got numerous errors that MyUserControl was not found (The name 'MyUserControl' does not exist in the current context). Look, you moron, it's in the solution!! Anyway, I searched the web and discovered that even if I do load the web user control dynamically, I should also add a <@ register..> tag to the aspx, as if I would have the user control on the page.
Easiest way is to move the user control on the page, copy the register tag to the clipboard, undo the user control insertion, paste the register tag back.


baljeet said...

U r right with what u said. In my page(with ajax controls) m loading user control dynamically.My scenerio is smwhat different. On the click of a button i have to rebind datalist with deffrebt values inside the user control. everything is working fine except the user control contents are not refreshed When i refresh the page it looks updated. I m adding user control dynamically on the button click. what do u suggest?

Siderite said...

If you add the control in a parent that is inside an UpdatePanel, you also have to refresh the UpdatePanel. Use the instance method UpdatePanel.Update();

baljeet said...

yes dear it is working fine with updating updatepanel. But now it is suffering from one more problem. Actually i have a datalist inside the usercontrol. when it is loaded first time all the events are working fine. But after that events are not fired And also the usercontrol is not visible at all again. Everytime before adding user control to the panel, m clearing panel and specifying the id of user control also. Can u suggest smthing? Thanks for any sort of help

baljeet said...

I've done this. What i did now is i cleared the panel first and then assigned id to usercontrol.Earlier i was doing vice versa.Due to that the problem was with ids.Its working fine now.