Programatically Load User Controls

The other day I was working on a code behind form and I needed to dynamically load a UserControl and access its properties. I was stumped, but with a little help from the codejunkies at I was able to move on. Here is a little sample to demonstrate this technique.

This sample consists of 3 pages:

  • default.aspx -- the standard ASP.NET page
  • cbDefault.vb -- the codebehind page for default.aspx
  • ucHeading.ascx -- a usercontrol with a property called page heading.

default.aspx simply has a panel object as a placeholder, and references the code behind file.


<%@ Page EnableSessionState="false" explicit="true" strict="true" MaintainState="false" inherits="cbDefault" src="cbDefault.vb"%>
<body bgcolor="#FFFFFF" >
<asp:panel id="pnlHeading" runat="server" />

ucHeading has a single property called PageHeading. PageHeading is a string that is used to display the heading of the page for the web surfer.


<script runat="server">
Private _pageheading as String = ""
Public Property PageHeading As String
    Return _pageheading
End Get
    _pageheading = value
End Set
End Property

cdDefault.vb is the code behind file for default.aspx. It contains the meat of this demo. The logic of cbDefault.vb is:

  • Load the UserControl
  • Get the type of UserControl
  • Get access to the property "PageHeader"
  • Set the property "PageHeader"
  • Add the UserControl to the panel object on default.aspx


Option Strict On
Option Explicit On

Imports System
Imports System.Reflection
Imports System.Web.UI
Imports System.Web.UI.WebControls

Public Class cbDefault : Inherits Page
Public pnlHeading as Panel

Public Sub Page_Load(Src As Object, E As EventArgs)
  ' Load the control
  Dim myUC as UserControl = LoadControl("ucHeading.ascx")

  ' Set the Usercontrol Type
  Dim ucType as Type = myUC.GetType()

  ' Get access to the property
  Dim ucPageHeadingProperty as PropertyInfo = ucType.GetProperty("PageHeading")

  ' Set the property
  ucPageHeadingProperty.SetValue(myUC,"Access a Usercontrol from Code Behind",Nothing)

  pnlHeading.Controls.Add ( myUC )
End Sub

End Class

You might also like...


Dave Wanta


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“I invented the term Object-Oriented, and I can tell you I did not have C++ in mind.” - Alan Kay