如何创建新的按钮运行时

时间:2014-01-26 15:29:41

标签: vb.net button runtime

我在vb中使用此代码在运行时添加一个新按钮:

Sub AddButton(ByVal label As String, ByVal location As Point)

Dim b As Button

b = New Button
b.Location = location
b.Text = label
Me.Controls.Add(b)

End Sub

但是我想给它一个名字并获取/设置它的属性并给它新的事件 例如,给它一个点击事件,改变我的新按钮的文本。

由于

1 个答案:

答案 0 :(得分:0)

您将按钮命名为:

Sub AddButton(ByVal label As String, ByVal location As Point)
    '...
    b.Name = "MyButton"
    '...
End Sub

你添加一个这样的点击手柄:

Sub AddButton(ByVal label As String, ByVal location As Point)
    '...
    'Option 1:
    AddHandler b.Click, Sub(sender As Object, e As EventArgs) CType(sender, Button).Text = "NewText"

    'Option 2:
    AddHandler b.Click, AddressOf MyButtonClick
    '...
End Sub

Private Sub MyButtonClick(sender As Object, e As EventArgs)
    CType(sender, Button).Text = "NewText"
End Sub