Polaric
Polaric

Reputation: 61

Visual Basic Setting Labels in an Array

I'm writing a little program in Visual Basic in Studio '10. I have a series of eight arrays that I need to set text too in a for loop. I need to set the text based off of the label number(eg label 1 gets word1, label 2 gets word2) Is there a way to create a array, then set my existing labels inside this array so I can then say something such as

for i = 1 to 8
    subsets(i).Text = words(w + i)
next   

Upvotes: 0

Views: 13879

Answers (3)

SubtleStu
SubtleStu

Reputation: 158

I think this is what you were trying to do, though I may be wrong

Public Class Form1

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim words() As String = {"one", "two", "three", "four", "five", "six", "seven", "eight"}
    Dim subsets() As Control = {Label1, Label2, Label3, Label4, Label5, Label6, Label7, Label8}

    For i = 0 To 7
        subsets(i).Text = words(i)
    Next

End Sub
End Class

This assigns the words array to the labels text property

Upvotes: 1

Mark Hall
Mark Hall

Reputation: 54532

Since you want to base the word on the label's name, you should make an array or a list as Oded suggested. You can then use the String.Remove method to remove the word Label from your labels name, cast it to an int and subtract 1 since arrays in .Net are 0 based.

Something like this.

Public Class Form1

    Dim subsets(7) As Label
    Dim words() As String = New String() {"this", "is", "a", "test", "of", "text", "replacement", "."}
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.
        subsets(0) = Label1
        subsets(1) = Label2
        subsets(2) = Label3
        subsets(3) = Label4
        subsets(4) = Label5
        subsets(5) = Label6
        subsets(6) = Label7
        subsets(7) = Label8

    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        For Each lbl As Label In subsets
            lbl.Text = words(CInt(lbl.Name.Remove(0, 5)) - 1)
        Next
    End Sub
End Class

Upvotes: 1

Oded
Oded

Reputation: 499062

You can create an array (or list) of Label and add each label control to it.

This will allow you to loop and assign values as you describe.

Dim subsets As New List(Of Label)
subsets.Add(label1)
subsets.Add(label2)
...

Upvotes: 2

Related Questions