Ask the Expert

How do I create a control array in VB.NET?

How do I create a control array in VB.NET? The control should have the same name and should be referenced by using index. I am working in Windows 2000.
OK, first's first, .NET control arrays differ very much from that of former VB6, and to be honest, the reason why was that conceptually, a control was something different than a class.

To create a control array in Visual Basic .NET requires that you now change your perception to seeing that everything is just a class.

The following code will help in resolving your issue -- just change the widget for any class that takes you fancy.

Public Class ControlArrayExample

    Private _mycollection As System.Collections.ArrayList = New System.Collections.ArrayList()

    Public ReadOnly Property Count() As Integer
        Get
            If (Not _mycollection Is Nothing) Then
                Return _mycollection.Count
            End If
            Return 0
        End Get
    End Property

    Public ReadOnly Property Item(ByVal Index As Integer) As Widget
        Get
            If (Index > 0) And (Index <= Me.Count) Then
                Return CType(_mycollection.Item(Index - 1), Widget)
            End If
            Return Nothing
        End Get
    End Property


    Public Sub AddItem(ByVal ValueIn As Widget)

        If (Not _mycollection Is Nothing) Then
            _mycollection.Add(ValueIn)
        End If

    End Sub

    Public Class Widget

        Private _myName As String

        Public Property Name() As String
            Get
                Return _myName
            End Get
            Set(ByVal Value As String)
                _myName = Value
            End Set
        End Property

        Public Sub New()

        End Sub
        Public Sub New(ByVal NameIn As String)
            Me.Name = NameIn
        End Sub

    End Class

End Class

Hope that works out for you.

This was first published in March 2003

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: