如何将代码分配给代码创建按钮?

时间:2015-07-23 21:01:11

标签: vb.net

我正在vb 2010中写一些东西,我所做的是一个带有“new”按钮的Form,它显示了一个新的表单,它是由代码在执行时创建的,这个表单包含一个文本框和另外两个按钮。问题是,如何为创建的按钮b1或b2添加代码?当我单击一个按钮或其他内容时,如何将文本框中的数据存储在变量中。我已经阅读了一些帖子,询问类似的东西,但它们都与VBA有关。我在下面写了整个代码。谢谢你的帮助。

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim f As New Form  
Dim TB As New TextBox
    Dim b1, b2 As New Button
    Dim l As New Label
    With f
        .Size = New System.Drawing.Size(220, 120)
        .StartPosition = FormStartPosition.CenterParent
        .Text = "new"
        .MinimizeBox = False
        .MaximizeBox = False
        .Controls.Add(b1)
        .Controls.Add(b2)
        .Controls.Add(TB)
        .Controls.Add(l)
    End With
    With l
        .Size = New System.Drawing.Size(180, 20)
        .Location = New Point(10, 3)
        .Text = "label"
    End With
    With TB
        .Size = New System.Drawing.Size(180, 30)
        .Location = New Point(10, 20)
        .Text = ""
    End With
    With b1
        .Size = New System.Drawing.Size(70, 30)
        .Location = New Point(30, 50)
        .Text = "create"
    End With
    With b2
        .Size = New System.Drawing.Size(70, 30)
        .Location = New Point(120, 50)
        .Text = "cancel"
    End With
    f.Show()

End Sub

1 个答案:

答案 0 :(得分:0)

为了显示文本框文本问题,您可以将lambda表达式用于处理程序,该表达式将所有变量保留在范围内,并允许您直接访问文本框。

... code above from your example ...
With b2
    .Size = New System.Drawing.Size(70, 30)
    .Location = New Point(120, 50)
    .Text = "cancel"
End With

AddHandler b1.Click, Sub(s, e2)
                         MsgBox(TB.Text)
                     End Sub

f.Show()