On Fri, Nov 12, 2010 at 11:13 AM, Rocky <[email protected]> wrote:

> Use arraylist
>
> On Nov 11, 4:58 pm, pinastro <[email protected]> wrote:
> > I have worked in VB 6 . creating an Object array was too simple in
> > that.
> > But how do we create Object Array in VB 2005 ?
> >
> > URGENT




Hello Karteek,

Here is a sample making a control array of 4 labels.  If you have only a few
controls, the commented code listing each control one by one may be used.



For a large number of controls, you may use the For Each loop.  The numbered
order of the controls is reversed so you may need to start with the
upperbound value + 1 and count backwards.  The sample code below works as
written if you have no more than 4 labels.



============================================================

Public Class Form1

Private LabelArray() As Label = New Label(4) {}

'declare an array of labels



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

SetControlArray()

End Sub



Sub SetControlArray()

Dim count As Integer, lbl As Label

count = 5

For Each ctl As Control In Controls

    If TypeOf ctl Is Label Then

        lbl = CType(ctl, Label)

        count -= 1

        LabelArray(count) = lbl

    End If

Next

'LabelArray(1) = Label1        'This code may be used instead of the For
Each block

'LabelArray(2) = Label2

'LabelArray(3) = Label3

'LabelArray(4) = Label4

End Sub



Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
AsSystem.EventArgs)
Handles Button1.Click

'Button1 clears the text in the array of labels

Dim a As Integer

For a = 1 To 4

    LabelArray(a).Text = ""

Next

End Sub



Private Sub Button2_Click(ByVal sender As System.Object, ByVal e
AsSystem.EventArgs)
Handles Button2.Click

'Button2 restores the text in the array of labels

Dim a As Integer

For a = 1 To 4

    LabelArray(a).Text = "Label" & a.ToString

Next

End Sub

End Class

============================================================



If you have 70 buttons in an array and additional buttons not in the array,
then you can add a Tag property to some of them and either include or
exclude the ones you need.  For example, in the For Each block, you can add
a fifth label and exclude it from the array by tagging it and using this
code:



count = 5

For Each ctl As Control In Controls

    If TypeOf ctl Is Label And CType(ctl.Tag, String) <> "n" Then

        lbl = CType(ctl, Label)

        count -= 1

        LabelArray(count) = lbl

    End If

Next

Reply via email to