I am adding web user controls to the page dynamically. Using the LoadControl
method, which only accepts a virtual path pointing to .ascx
, works very nicely. However, overloading the LoadControl
, which takes a type and an array of parameters, causes me some headaches.
The web user control is created as expected, but the controls contained in the web user control are null and I get an exception as soon as I try to work with them. Strange, because it works when using the first version of LoadControl
.
Web user management, simple with the Literal
control:
<%@ Control Language="vb" AutoEventWireup="false" CodeBehind="MyControl.ascx.vb" Inherits="MyControl" %> <asp:Literal ID="myLiteral" runat="server"></asp:Literal>
The control code is behind:
Public Class MyControl Inherits System.Web.UI.UserControl Public Property Data As MyData Public Sub New() End Sub Public Sub New(data As MyData) Me.Data = data End Sub Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load myLiteral.Text = Data.ID ' The Literal is null, but ONLY when I use the second LoadControl() method! End Sub End Class
And the corresponding code from .aspx
from which I am trying to dynamically load the control:
Private Sub Page_Init(sender As Object, e As System.EventArgs) Handles Me.Init Dim x = LoadControl(GetType(MyControl), New Object() {New MyData With {.ID = 117}}) Page.Controls.Add(x) ' Using LoadControl("MyControl.ascx") works as expected! End Sub
source share