Programatically Adding Controls to Form in vb .net

larrythek1
01-06-2004, 10:31 AM
I know I'm still hung up over the lack of Control Arrays in vb .net, but is there an easier way to dynamically add controls to a form than what I show below?

Thanks,
Larry

Dim MyText1 As New TextBox()
Dim MYText2 As New TextBox()
Dim MyText3 As New TextBox()

MyText1.Location = New Point(25, 25)
Me.Controls.Add(MyText1)
MyText1.Text = "Text1"

MYText2.Location = New Point(25, 50)
Me.Controls.Add(MYText2)
MYText2.Text = "Text2"

MyText3.Location = New Point(25, 75)
Me.Controls.Add(MyText3)
MyText3.Text = "Text3"

Optikal
01-06-2004, 12:43 PM
That look about right. You can look at the InitializeComponents method that VS.Net generates for you to see how they do it if you want to learn more, but your code looks about right.

OnErr0r
01-06-2004, 12:49 PM
Here's how I'd do a control array:


Option Explicit On
Option Strict On

Public Class Form1
Inherits System.Windows.Forms.Form
Private txtArray() As TextBox
Private Const NUM_ITEMS As Integer = 3

+#Region " Windows Form Designer generated code "

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim i As Integer

ReDim txtArray(NUM_ITEMS - 1)

For i = 0 To NUM_ITEMS - 1
txtArray(i) = New TextBox
Controls.Add(txtArray(i))
txtArray(i).Location = New Point(25, i * 25)
txtArray(i).Text = "Text" & i.ToString
txtArray(i).Name = "Text" & i.ToString
AddHandler txtArray(i).TextChanged, New System.EventHandler(AddressOf txtArray_TextChanged)
Next i
End Sub

Private Sub txtArray_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs)
Dim txt As TextBox = DirectCast(sender, TextBox)
Debug.WriteLine(txt.Text & " " & txt.Name)
End Sub
End Class

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum