Question

Hey all i am creating some run-time label for my form:

    Dim tmpLbl As New Label
    Dim intX As Integer = 0

    Do Until intX = 4
        With tmpLbl
            .Size() = New System.Drawing.Size(58, 15)
            .Text = "Run-time Controls " & intX
            .Location = New System.Drawing.Point(2, 20)
            .Name = "test" & intX
        End With

        With Me.Controls
            .Add(tmpLbl)
        End With

        intX += 1
    Loop

This works just fine... but when i want to, say place a button on the form that calls one of these run-time controls like so:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    Debug.Print(tmpLbl.Name)
End Sub

Naturally this above does not work. how can i get a labels name (ex: test2) and read its text (ex: Run-time Controls 2) when i click on that button?

Was it helpful?

Solution

Got it!

Private genTmpLbl As New List(Of Label)

Public Sub makeRunTimeControls()
    Dim tmpLbl As New Label
    Dim intX As Integer = 0

    Do Until intX = 4
        With tmpLbl
            .Size() = New System.Drawing.Size(58, 15)
            .Text = "Run-time Controls " & intX
            .Location = New System.Drawing.Point(2, 20)
            .Name = "test" & intX
        End With

        With Me.Controls
            .Add(tmpLbl)
        End With

        genTmpLbl.Add(tmpLbl)
        intX += 1
    Loop
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    For Each label In genTmpLbl
        For Each control In Me.Controls
            If TypeOf (control) Is Label Then
                Debug.Print(control.Name)
            End If
        Next
    Next
End Sub
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top