ASP.NET, VB.NET  •  Build a DynamicControlHost Control

Listing 1. You can build a control that makes using dynamic controls and building encapsulated processes easy. Once you have the control, it can take as little as one line of code to have a control load dynamically with full state management.

Public MustInherit Class DynamicControlHost
   Inherits System.Web.UI.UserControl
   Protected WithEvents pnlHost As _
      System.Web.UI.WebControls.Panel

   'Web Form Designer Generated Code Here.
   Dim m_strUserControl As String = ""

   Private ReadOnly Property UniqueKey() _
      As String
      Get
         Return Me.UniqueID & "DynamicControl"
      End Get
   End Property
   Private Sub Init2_Load(ByVal sender As _
      System.Object, ByVal e As _
      System.EventArgs) Handles MyBase.Init
      'Now change the ID of this control to that
      'of what it was previously if it is a
      'postback
      If Me.Page.IsPostBack Then
         If Me.UserControlPath.Length <> 0 Then
            Me.pnlHost.Controls.Add(Page. _
               LoadControl(Me.UserControlPath))
         End If
      End If
   End Sub
   Property UserControlPath() As String
      Get
         If m_strUserControl.Length = 0 Then
            If Not Request.Form(Me.UniqueKey) _
               Is Nothing Then
               m_strUserControl = Request. _
                  Form(Me.UniqueKey)
            End If
         End If
         Return m_strUserControl
      End Get
      Set(ByVal Value As String)
         If Me.pnlHost.Controls.Count > 0 Then
            ' check that the current control
            ' isn't the same as this new one
            If Me.UserControlPath <> Value Then
               ' Remove old items because we
               ' can't simply replace them!
               Me.pnlHost.Controls.Remove _
                  (Me.pnlHost.Controls(0))
               ' Add New Items
               Me.pnlHost.Controls. _
                  Add(Page.LoadControl(Value))
               ' Store the new values
               m_strUserControl = Value
            End If
         Else
            Me.pnlHost.Controls. _
               Add(Page.LoadControl(Value))
            m_strUserControl = Value
         End If
      End Set
   End Property

   ReadOnly Property UserControl() As Control
      Get
         Return Me.pnlHost.Controls(0)
      End Get
   End Property

   Protected Overrides Sub Render(ByVal writer _
      As System.Web.UI.HtmlTextWriter)
      ' We want to include an HTML Form field to
      ' store the current UI Object
      MyBase.Render(writer)
      writer.Write("<input type=""hidden"" name=
         """ & Me.UniqueKey & """value=""" & _
            Me.UserControlPath & """/>")
   End Sub
End Class