Inheriting System.UI.ControlCollection for a WebControl - FindControl doesn't work???

H

Harry F. Harrison

Here's the situation...Context - Using an Inherited WebControl object as a
base for server custom controls.

In a web custom control, whenever I create a child control and add it to the
Controls class, it takes 3 lines of code.

Example:

Dim TextBox as System.Web.UI.WebControls.TextBox
1..TextBox = New System.Web.UI.WebControls.TextBox
2..TextBox.ID = "myTextBox"
3..Controls.Add(TextBox)

I would like to overload the Controls object in WebControl to do this in one
line of code.

Controls.Add(New System.Web.UI.WebControls.TextBox, "myTextBox")

HOWEVER...

I don't think I've got everything glued together. For example: FindControl
doesn't return any controls that exist in my custom object. It is still
looking at myBase.Controls (I think). If I need to override FindControl,
are there other methods that I need to override as well, or am I going down
the wrong path?

'sample code
Public Class MyControl

Inherits CompositeWebControl

Protected Overrides Sub CreateChildControls()
Controls.Add(New System.Web.UI.WebControls.TextBox, "myTextBox")

End Sub

Protected Overrides Sub Render(ByVal writer As
System.Web.UI.HtmlTextWriter)
'breaks on this method - FindControl returns Nothing

FindControl("myTextBox").RenderControl(writer)

End Sub

End Class


Option Explicit On
Option Strict On

'inherited WebControl - use as a base for new WebControls

Public Class CompositeWebControl
Inherits System.Web.UI.WebControls.WebControl

Implements System.Web.UI.INamingContainer

Private mobjControls As WebControlCollection

Protected Overrides Function CreateControlCollection() As
System.Web.UI.ControlCollection

If (mobjControls Is Nothing) Then

mobjControls = New WebControlCollection(Me)

End If

Return CType(mobjControls, System.Web.UI.ControlCollection)

End Function

<System.ComponentModel.Browsable(False)> _

Public Shadows ReadOnly Property Controls() As WebControlCollection

Get

Me.CreateControlCollection()

Me.EnsureChildControls()

Return mobjControls

End Get

End Property

End Class

'custom ControlCollection that has an overloaded Add method...

Public Class WebControlCollection
Inherits System.Web.UI.ControlCollection

Sub New(ByVal owner As System.Web.UI.Control)

MyBase.New(owner)

End Sub

Public Overloads Sub Add(ByVal child As System.Web.UI.Control, ByVal ID
As String)

child.ID = ID

Me.Add(child)

End Sub

End Class
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,818
Latest member
Brigette36

Latest Threads

Top