单击按钮时需要数据的运行时控件

时间:2013-07-16 19:38:12

标签: vb.net controls labels

嘿,我正在为我的表单创建一些运行时标签:

    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

这很好用......但是当我想要时,比如在窗体上放置一个按钮来调用其中一个运行时控件,如下所示:

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

自然以上这个不起作用。当我点击该按钮时,如何获得标签名称( ex:test2 )并阅读其文本( ex:运行时控件2 )?

1 个答案:

答案 0 :(得分:0)

知道了!

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