Question Text box array?

robotic

New member
Joined
Oct 5, 2009
Messages
1
Programming Experience
Beginner
Hi im new here and am at beginer level vb.net. I have two basic questions on relating to upgrading code from vb6 to .net:

I have what seems to be text box array...
in the old code they are referenced as Text1(i).Text
to facilitate looping with an If statement
but i cannot make this work in vb.net
example code

For i = 0 To 4
If Not IsNumeric(Text1(i).Text) Then
MsgBox Character(i, 1)
Exit Sub
End If
If Text1(i).Text = "" Then
MsgBox Character(i, 0)
Exit Sub
End If
Next

this code iterates thru 5 text boxes to check that the value entered is numeric and also that there are no blank spaces.

How would i put this into .net as it doesn't seem possible to hold the text boxes in array.
many thanks for any suggestions!
 
Control arrays never made it over to dot net unfortunately. You can itterate through a control collection but it doesnt work quite like the old control arrays.
 
Yes they still exist in VB.Net

VB.NET:
Dim TextBoxes() as TextBox = {TextBox1, TextBox2}
TextBoxes(0).Text = "Hello"
 
As mentioned in the discussion, control arrays no longer exists in .NET. When migrating this feature, the approach we took was to create the individual controls (so they would work in the designer) and add them to an array so the code can keep working as it did before.

So, for the example you had (assuming some things), the code would be:

VB.NET:
Dim _Text1_0 As System.Windows.Forms.TextBox
Dim _Text1_1 As System.Windows.Forms.TextBox 
Dim _Text1_2 As System.Windows.Forms.TextBox 
Dim _Text1_3 As System.Windows.Forms.TextBox 
Dim _Text1_4 As System.Windows.Forms.TextBox 
...
Dim Text1(5) As System.Windows.Forms.TextBox
...
Text1(0) = _Text1_0
Text1(1) = _Text1_1
Text1(2) = _Text1_2
Text1(3) = _Text1_3
Text1(4) = _Text1_4

You can then keep the same logic as before.
 
You can do it as in the sample below, which includes 5 textboxes. Use the Tag property for the textboxes within the array if you have other textboxes that are not part of the array.


VB.NET:
Public Class Form1
    Private TextArray(5) As TextBox

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim count As Integer = 5
        Dim txt As TextBox
        For Each ctl As Control In Controls
            If TypeOf ctl Is TextBox Then
                txt = CType(ctl, TextBox)
                'If CType(txt.Tag, Integer) = 1 Then   'Use only if textboxes are Tagged
                TextArray(count) = txt
                count -= 1
                'End If
            End If
        Next
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        For x As Integer = 1 To 5   'will also work with 0 To 5 if 6 textboxes used
            TextArray(x).Text = x.ToString
        Next
    End Sub

End Class
 
Back
Top