locked
How to create an array of textboxes?

    Question

  • I want to create an array of textboxes to populate a form. I have the following code, but it is not working. I would appreciate any help, please.
    Public Class Form1
    
      Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
        Dim count As Integer
        Dim xLoc As Integer
        Dim yLoc As Integer
        Dim TestCtrl(4) As TextBox
    
        xLoc = 13
        yLoc = 34
    
        For count = 0 To 3
          MsgBox("count = " & count)
          TestCtrl(count).Location = New System.Drawing.Point(xLoc, yLoc)
          TestCtrl(count).Name = "txtTestCtrl" & count
          TestCtrl(count).Text = "Test"
          Me.Controls.Add(TestCtrl(count))
          count = count + 1
          MsgBox("count = " & count)
          yLoc = yLoc + 25
        Next count
      End Sub
    Friday, December 03, 2010 3:34 PM

Answers

  • This line: Dim TestCtrl(4) As TextBox defines an array that will contain TextBoxes. It does NOT create any of the TextBoxes. So you need to individually create each TextBox and add it to the array.

    Something like this (not syntax checked):

    for count as Integer = 0 to 3
       Dim tb as New TextBox
       tb.Location = ...
       tb.Name = ...
       tb.Text = ...
       Me.Controls.Add(tb)
       TestCtrl(count) = tb <-- This line adds the TextBox to the array.
       yLoc += 25
    Next count

    NOTE: You don't need/want the line that increments count (count = count + 1). The For loop will do that for you.

    Hope this helps.


    www.insteptech.com ; msmvps.com/blogs/deborahk
    We are volunteers and ask only that if we are able to help you, that you mark our reply as your answer. THANKS!
    • Marked as answer by VBNewLearner Friday, December 03, 2010 4:20 PM
    Friday, December 03, 2010 4:02 PM

All replies

  • This line: Dim TestCtrl(4) As TextBox defines an array that will contain TextBoxes. It does NOT create any of the TextBoxes. So you need to individually create each TextBox and add it to the array.

    Something like this (not syntax checked):

    for count as Integer = 0 to 3
       Dim tb as New TextBox
       tb.Location = ...
       tb.Name = ...
       tb.Text = ...
       Me.Controls.Add(tb)
       TestCtrl(count) = tb <-- This line adds the TextBox to the array.
       yLoc += 25
    Next count

    NOTE: You don't need/want the line that increments count (count = count + 1). The For loop will do that for you.

    Hope this helps.


    www.insteptech.com ; msmvps.com/blogs/deborahk
    We are volunteers and ask only that if we are able to help you, that you mark our reply as your answer. THANKS!
    • Marked as answer by VBNewLearner Friday, December 03, 2010 4:20 PM
    Friday, December 03, 2010 4:02 PM
  • Thank you very much for you help.

    Ray

    Friday, December 03, 2010 4:22 PM