control array vb.net

2020-05-01 05:11发布

Im trying to write a program in VB.net for a shopping system. It will read through the database and populate the items on the form. The app displays information such as product name etc in labels, inside a scrollable panel. Im creating the objects and assigning values such as text at runtime. I'm using a loop for the code.

If i was using vb 6, i would have a control array, and use the index and my counter to display the data. Since im doing this in vb.net, i have no way to do that.. Any solutions?

标签: vb.net
4条回答
地球回转人心会变
2楼-- · 2020-05-01 05:23

There are no Control arrays in VB.NET . But you could iterate through Panel.Controls collection. All the controls are in that collection (If they are all in the same panel).

    For i = 0 To Panel1.Controls.Count - 1

        Dim control = Panel1.Controls(i)

        'Do something with control..

    Next
查看更多
趁早两清
3楼-- · 2020-05-01 05:27

VB.NET doesn't have control arrays as such.

However, you can create an array of controls and assign your controls to each element of the array, though you could also use a List(Of Control).

This will allow you to loop over the collection.

查看更多
Animai°情兽
4楼-- · 2020-05-01 05:31

VB.NET does not support control arrays, in the same sense as VB6. You can do similar things, though. For instance, if you want to handle events from multiple controls with the same method, you can do so like this:

Private Sub MyClickHandler(sender As Object, e As EventArgs) Handles _
    Button1.Click, _
    Button2.Click, _
    Button3.Click

    Dim buttonThatWasClicked As Button = CType(sender, Button)
    ' Do something...
End Sub

If you want to create an array of controls that you can loop through, you can do that to, like this:

Dim myTextBoxes() As TextBox = New TextBox() { TextBox1, TextBox2, TextBox3 }
For i As Integer = 0 to myTextBoxes.Length - 1
    myTextBoxes(i).Text = ...
Next

Alternatively, if you name your controls consistently, you can find them by name in your form's Controls collection. For instance, if you had three text boxes named TextBox1, TextBox2, and TextBox3, you could loop through them like this:

For i As Integer = 1 to 3
    Dim t As TextBox = CType(Me.Controls("TextBox" & i.ToString()), TextBox)
    t.Text = ...
Next
查看更多
够拽才男人
5楼-- · 2020-05-01 05:37

First is there a reason why you can't use a grid for this? - that would be the obvious solution (as it would have been in VB6 as well).

ETA . . .but if you must, this code snippet will add a set of labels to your form. You will need to modify this eg replace the for next loop with a for each r as mydataset.mytabledatarow in mydataset.mydatable etc etc

   For i = 1 To 10
        Dim l As New Label
        l.Location = New System.Drawing.Point With {.x = 10, .y = i * 30}
        Me.Controls.Add(l)
        l.Text = "test " & i.ToString
   Next
查看更多
登录 后发表回答