Search code examples
asp.netcustom-server-controlsservercontrols

Simple Custom Server Control getting 'Value cannot be null. Parameter name: child'


Building my first server control. Getting the "Value cannot be null. Parameter name: child" error in debug at the point indicated in my code. The textbox is created, then becomes nothing when the parent's page_load event is called. The page_load event fires between the OnInit and CreateChildControls in my control. Examples are hard to come by.

Public Class ContactForm
Inherits WebControl

#Region "Local variables"
Private _ShowFirstName As Boolean
Private tbFirstName As TextBox
#End Region


<Browsable(True), _
Bindable(True), _
Category("Appearance"), _
DefaultValue(True), _
Localizable(True), _
Description("Show First Name field")> _
Public Property ShowFirstName() As Boolean
    Get
        Return _ShowFirstName
    End Get
    Set(value As Boolean)
        _ShowFirstName = value
    End Set
End Property

Protected Overrides Sub OnInit(e As EventArgs)
    If ShowFirstName = True Then
        Dim tbFirstName As New TextBox
        tbFirstName.ID = "tbFirstName"
        tbFirstName.MaxLength = 30
        tbFirstName.Text = "IM HERE"
    End If
    MyBase.OnInit(e)

End Sub

<<<<< --- NOTE: The Page_Load event of the parent fires here  ->>>>>

Protected Overrides Sub CreateChildControls()
    Me.Controls.Add(tbFirstName) <<---Error: Value cannot be null. Parameter name: child
    If HasChildViewState Then
        ClearChildViewState()
    End If
    MyBase.CreateChildControls()
End Sub

End Class

Solution

  • Okay, here is how I got it working.

    I basically move the OnInit code into the CreateChildControls...duh! I created a function (buildForm) that declares and adds all controls in one step like below.

     Protected Overrides Sub CreateChildControls()
        buildForm()
        If HasChildViewState Then
            ClearChildViewState()
        End If
        MyBase.CreateChildControls()
     End Sub
    

    SIDEBAR: Web User Control vs Custom Server Control I spent the last 4-5 days comparing and experimenting with both controls. I've done a lot of User Controls over the years and just copied them into applications. Hated the maintenance that created.

    I spent a full day trying to compile my current web controls into single dll that could be used kind of like server controls. I found it tedious and limited.

    Many articles, including MSDN, had me scared of server controls saying it is much harder than a web control to create. I can say...so far...I am digging the Server Control. I wish I had done this in the beginning. True reuse. Don't fear the server control.