在VB.Net中向按钮添加额外的控件

时间:2018-12-25 06:55:27

标签: vb.net

我有一个代码,可以在运行时在一个效果很好的表单上创建30个按钮

For i = 0 To 30
    btn = New Button
    Dim old As Padding = btn.Margin
    Dim old2 As Padding = btn.Padding
    btn.Tag = "X1"
    btn.Name = "Drane"
    btn.Text = "The power of trying"
    btn.Width = 95
    btn.Height = 120
    btn.Margin = New Padding(10, 10, 10, 10)
    btn.Padding = New Padding(0, 4, 0, 2)
    btn.TextAlign = ContentAlignment.BottomCenter
    btn.ImageAlign = ContentAlignment.TopCenter
    btn.Font = New Font("Lucida Sans Unicode", 11)
    btn.ForeColor = Color.Black
    btn.BackColor = Color.White
Next i

现在我正试图添加一个额外的控件来保存我在运行时创建的按钮的ID

btn.id = i

它将保存每个特定按钮的ID,以便我可以在应用程序的其他函数中获取值。我知道我必须以某种方式将其添加为控件,但我只是不知道如何。

解决该问题,请提供任何帮助

1 个答案:

答案 0 :(得分:1)

这将扩展Button类并添加一个ID属性。

Public Class ButtonMod
    Inherits Button

    Public Property ID As Integer

End Class

然后,您只需像已经做的那样就循环创建它们:

For i As Integer = 1 To 30
    Dim btn As New ButtonMod
    Dim old As Padding = btn.Margin
    Dim old2 As Padding = btn.Padding
    btn.Tag = "X1"
    btn.Name = "Drane"
    btn.Text = "The power of trying"
    btn.Width = 95
    btn.Height = 120
    btn.Margin = New Padding(10, 10, 10, 10)
    btn.Padding = New Padding(0, 4, 0, 2)
    btn.TextAlign = ContentAlignment.BottomCenter
    btn.ImageAlign = ContentAlignment.TopCenter
    btn.Font = New Font("Lucida Sans Unicode", 11)
    btn.ForeColor = Color.Black
    btn.BackColor = Color.White
    btn.ID = i
Next