Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
TitleDynamically load controls into a "control array" in VB .NET
DescriptionThis example shows how to dynamically load controls into a "control array" in VB .NET.
Keywordscontrol, control array, load control, AddHandler, VB.NET
CategoriesControls, VB.NET
 
This example make an array of TextBoxes. When you click the New TextBox button, the program enlarges the array and adds a new TextBox at the end. It positions the new control and saves its index in the its Tag property. (Alternatively you could use the control's name to identify it later.)

The program adds an event handler for the control's TextChanged event and adds the control to the form's Controls collection.

 
Private m_TextBoxes() As TextBox = {}

Private Sub btnNewTextBox_Click(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    btnNewTextBox.Click
    ' Get the index for the new control.
    Dim i As Integer = m_TextBoxes.Length

    ' Make room.
    ReDim Preserve m_TextBoxes(i)

    ' Create and initialize the control.
    m_TextBoxes(i) = New TextBox
    With m_TextBoxes(i)
        .Name = "TextBox" & i.ToString()
        If m_TextBoxes.Length < 2 Then
            ' Position the first one.
            .SetBounds(8, 8, 100, 20)
        Else
            ' Position subsequent controls.
            .Left = m_TextBoxes(i - 1).Left
            .Top = m_TextBoxes(i - 1).Top + m_TextBoxes(i - _
                1).Height + 4
            .Size = m_TextBoxes(i - 1).Size
        End If

        ' Save the control's index in the Tag property.
        ' (Or you can get this from the Name.)
        .Tag = i
    End With

    ' Give the control an event handler.
    AddHandler m_TextBoxes(i).TextChanged, AddressOf _
        TextBox_TextChanged

    ' Add the control to the form.
    Me.Controls.Add(m_TextBoxes(i))
End Sub
 
When you enter text in one of the TextBoxes, the TextBox_TextChanged event handler displays the control's name and its current text.
 
' The user entered some text.
Private Sub TextBox_TextChanged(ByVal sender As _
    System.Object, ByVal e As System.EventArgs)
    ' Display the current text.
    Dim txt As TextBox = DirectCast(sender, TextBox)
    Debug.WriteLine(txt.Name & ": [" & txt.Text & "]")
End Sub
 
 
Copyright © 1997-2006 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated