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!

有帮助吗?

解决方案

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)

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top