:o( .... Can't make a simple composite control work

M

M O J O

Hi,

I'm playing around with creating composite controls.

I want to create a composite web control, that will create 10 textboxes
and be able to return all their text values.

Here's my code so far...

--------------------------------------------------------------------------

Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Text
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Collections.Specialized


<DefaultProperty("Type"), ToolboxData("<{0}:MyTextBox
runat=server></{0}:MyTextBox>")> _
Public Class MyTextBox
Inherits CompositeControl

Dim arr As Generic.List(Of TextBox)


Protected Overrides Sub RenderContents(ByVal output As HtmlTextWriter)
If Not (Site Is Nothing) Then
' In design mode...
output.Write("TextBox")
Else
' In runtime...
Call EnsureChildControls()
Call RenderChildren(output)
End If
End Sub


Protected Overrides Sub CreateChildControls()
Dim arr As New Generic.List(Of TextBox)
For i As Integer = 0 To 10
Dim t As New TextBox
arr.Add(t)
Me.Controls.Add(t)
Next
End Sub


Public Function GetAllText() As String
Me.EnsureChildControls()

Dim sb As New System.Text.StringBuilder

For Each t As TextBox In arr ' <- Error!!
sb.Append(t.Text & vbCrLf)
Next

Return sb.ToString
End Function

End Class

--------------------------------------------------------------------------

But I can't make it work.

In the GetAllText function, the arr variable is nothing eventhough I
called the EnsureChildContols method.

What am I doing wrong, and what is the best way (practice) of creating
such a composite control? Can I do it better differently?

Thanks!!

M O J O
 
T

Teemu Keiski

Hi,

you basically instantiate a local generic array in CreateChildControls
(local to the method) and therefore the global one, declared in class body,
actually never gets assigned anything.

Change the code in CreateChildControls to:

Protected Overrides Sub CreateChildControls()
'NOTE THIS LINE
arr = New Generic.List(Of TextBox)

For i As Integer = 0 To 10
Dim t As New TextBox
arr.Add(t)
Me.Controls.Add(t)
Next
End Sub
 

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,994
Messages
2,570,223
Members
46,813
Latest member
lawrwtwinkle111

Latest Threads

Top