troubleshooting Question

Where to create child control objects - property accessors (get) or CreateChildControls

Avatar of netsmithcentral
netsmithcentralFlag for United States of America asked on
.NET ProgrammingVisual Basic.NETASP.NET
4 Comments1 Solution486 ViewsLast Modified:
I know the .NET system is designed for custom controls to create their child control methods in the CreateChildControls method, and then call EnsureChildControls() before accessing any of their properties, like the following example:
Protected Overrides Sub CreateChildControls()
            _txtSearch = New TextBox()
            Me.Controls.Add(_txtSearch)
        End Sub

        Public Property Text As String
            Get
                EnsureChildControls()
                Return _txtSearch.Text
            End Get
            Set(ByVal value As String)
                EnsureChildControls()
                _txtSearch.Text = value
            End Set
        End Property

I don't see why this is necessary.  Couldn't we just use a property accessor model, create controls there, and add them to the controls collection in CreateChildControls?  That would eliminate the need for using/remembering to call EnsureChildControls() on property access!  FYI, I have tested this method and it works fine.
Private _txtSearch As TextBox = Nothing
        Private ReadOnly Property txtSearch As TextBox
            Get
                If _txtSearch Is Nothing Then
                    _txtSearch = New TextBox()
                End If

                Return _txtSearch
            End Get
        End Property

        Protected Overrides Sub CreateChildControls()
            Me.Controls.Add(txtSearch)
        End Sub

Is there some reason I'm missing to use the EnsureChildControls model instead of the property accessor model?
ASKER CERTIFIED SOLUTION
Member_6283346

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 4 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros