visual basic 2015:如何使用按钮单击事件更改动态创建的标签的文本

时间:2017-03-30 15:43:27

标签: vb.net

我有一个动态创建的标签页,我在其中动态创建了一个按钮和标签。我试图找出如何使用button.click事件更改label.text。一切正常,直到我添加With / End With来更改按钮单击子例程中的标签文本。这是我第一次尝试动态编程(我的爱好,所以试图学习),但我确实有一个特定的最终目标。有关如何解决这个问题的任何想法?

Private Sub initialize_Button()
    Dim button_Mybutton As New Button
    With button_Mybutton
        .Name = "button_My_Button"
        .AutoSize = True
        .Text = "Calculate"
        .Visible = True
        .Top = 200
        .Left = 10
    End With
    AddHandler button_Mybutton.Click, AddressOf Me.button_Click
    Me.Controls.Add(button_Mybutton)
End Sub

Protected Sub button_Click(ByVal sender As Object, ByVal e As EventArgs)
    MsgBox("Button Clicked")
    With label_Test
        .text = "Test Confirmed"
    End With
End Sub

Private Sub label_Test_Output()
    Dim label_Test As New Label
    With label_Test
        .Name = "label_Test"
        .Top = 200
        .Left = 100
        .AutoSize = True
        .Text = "Label Test"
        .Visible = True
    End With
    Me.Controls.Add(label_Test)
End Sub

1 个答案:

答案 0 :(得分:0)

将方法之外的控件声明移动到类级别。然后你可以从班上的任何地方访问它们。

Private button_Mybutton As Button
Private label_Test As Label

Private Sub initialize_Button()
    button_Mybutton = New Button()
    With button_Mybutton
        .Name = "button_My_Button"
        .AutoSize = True
        .Text = "Calculate"
        .Visible = True
        .Top = 200
        .Left = 10
    End With
    AddHandler button_Mybutton.Click, AddressOf Me.button_Click
    Me.Controls.Add(button_Mybutton)
End Sub

Protected Sub button_Click(ByVal sender As Object, ByVal e As EventArgs)
    MsgBox("Button Clicked")
    If label_Test IsNot Nothing Then
        With label_Test
            .text = "Test Confirmed"
        End With
    End If
End Sub

Private Sub label_Test_Output()
    label_Test = New Label()
    With label_Test
        .Name = "label_Test"
        .Top = 200
        .Left = 100
        .AutoSize = True
        .Text = "Label Test"
        .Visible = True
    End With
    Me.Controls.Add(label_Test)
End Sub

您还应该检查标签是否在访问时创建,因为在调用label_Test_Output之前您可以单击该按钮。向处理程序添加了空检查。