title: Load user control programmatically using LoadControl(Type, Object())
body: <p>I’m adding web user controls to a page dynamically. Using the <code>LoadControl</code> method that only takes a virtual path pointing to the <code>.ascx</code> works pretty nicely. However, the overload of <a href="http://msdn.microsoft.com/en-us/library/ewtd66a0.aspx" rel="noreferrer"><code>LoadControl</code></a> that takes a type and an array of parameters is causing me some headaches. </p>
  
  <p>The web user control is instantiated as expected, but the controls contained within the web user control are null and I get an exception as soon as I try to work with them. Strange, because it’s working when use the first version of <code>LoadControl</code>.</p>
  
  <p>The web user control, simple, with a <code>Literal</code> control:</p>
  
  <pre><code>&lt;%@ Control Language="vb" AutoEventWireup="false" CodeBehind="MyControl.ascx.vb" Inherits="MyControl" %&gt;
  &lt;asp:Literal ID="myLiteral" runat="server"&gt;&lt;/asp:Literal&gt;
  </code></pre>
  
  <p>The controls' code behind:</p>
  
  <pre><code>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
  </code></pre>
  
  <p>And the relevant code from the <code>.aspx</code> from which I'm trying to dynamically load the control:</p>
  
  <pre><code>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
  </code></pre>