Frage

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!

War es hilfreich?

Lösung

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)

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top