1
votes

My program has the ability to add textboxes during run time. The amount of textboxes on the form at run time is stored in the variable i. I need to create an array that stores all of the values from each of the textboxes in a place in the array up to the value of i. All of the textboxes have names that count upwards. Example:

  • Textbox1
  • Textbox2
  • Textbox3

And so on. In summary, is there any way I can store the values of i amount of textboxes, in an array? Any help will be appreciated, thanks.

Additional note:

  • This program is kind of like a registration form, besides the fact that there could be any amount of textboxes on the form to store in the array.
  • The procedure that would add the values of the textboxes to an array will be triggered by a button press, so i cannot add add the values of the textboxes as they are created.
2
Rather than using an array to store references to the TextBoxes, you would very probably be better off using a List(Of TextBox), as implied by Marc Johnston's answer. - Andrew Morton

2 Answers

2
votes

When you create the textboxes at runtime, add the textbox into a list, similar to below:

    Dim textboxes As New List(Of TextBox)
    For I = 1 To 3
        Dim tb As New TextBox
        textboxes.Add(tb)
    Next

Then you can enumerate the list and process each textbox separately. Similar to below:

    For Each tb As TextBox In textboxes
        Dim value As String = tb.Text
    Next
1
votes

You can use a dictionary to store the index of each text box and the associated text box value. Define the dictionary like this:

Dim dict As New Dictionary(Of String, String)

Populate it like this:

For index As Integer = 0 To 5
    dim txtBox = new TextBox
    txtBox.Name = index ' we'll make this index the name
    MyForm.Controls.Add(txtBox);
    dict.Add(index, txtBox )
Next

Then use it like this: (for example, when text changes and the text control is sender)

dim txtBox = (TextBox)sender;
dict(txtBox .Name) = txtBox .Text

Here are a couple of links for references to what I used above:

And take the code samples with a grain of salt. I'm not on a machine with an IDE.