Question

I want to render a usercontrol dynamicly but my code doesn't work as expected. The codebehind won't be executed. Here is my code for rendering:

Dim ucControl As UserControl = LoadControl(pControl.VirtualPath & "/" & Control & ".ascx")

Dim ucSB As New StringBuilder
Dim ucSW As New StringWriter(ucSB)
Dim ucHTML As New HtmlTextWriter(ucSW)

ucControl.RenderControl(ucHTML)

Thank you for your help!

Était-ce utile?

La solution

When rendering a UserContorl the normal lifecycle events are not called. This behavior is by design.

You could cast the UserControl to your type and call the methods explicitly:

Dim ucControl As MyUserControl = Ctype(LoadControl(pControl.VirtualPath & "/" & Control & ".ascx"), MyUserControl)

ucControl.Page_Load(me, EventArgs.Empty)

Autres conseils

Another option is to add the dyncamically loaded control to your page as early as possible in the page lifecycle, so that the event wil be called.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top