VB.NET中如何动态创建控件
比如我想在Form1窗口上建5个Button1,然后再逐一删除,希望给个代码做参考。谢谢,还有个小问题就是如果在生成的程序中,可以手动随便托动Button1按钮位置。
[解决办法]
Sub AddButton(ByVal sender As Object, ByVal e As System.EventArgs)
Dim NewButton As New Button
Static Dim ButtonID As Integer = 0
ButtonID += 1
With NewButton
.Location = New Point(10, ButtonID * 40) 'New Point(Form1.Label1.Text, Form1.Label2.Text)
.Size = New System.Drawing.Size(79, 29)
.TabIndex = 0
.UseVisualStyleBackColor = True
.Name = "Button" & ButtonID 'TextBox1.Text
.Text = "Button" & ButtonID 'TextBox1.Text
'AddHandler .MouseDown, AddressOf _MouseDown '绑定事件处理程序
'AddHandler .MouseMove, AddressOf _MouseMove
'AddHandler .Click, AddressOf _Click '绑定事件处理程序
End With
Me.Controls.Add(NewButton) '添加进from
End Sub
Sub DelButton(ByVal sender As Object, ByVal e As System.EventArgs)
Dim ButtonID As Integer
ButtonID = sender.Tag '获取标识
Dim NowButton As Button
NowButton = ButtonCollection("Button" & ButtonID) '获取button
RemoveHandler NowButton.Click, AddressOf DelButton '移除绑定事件
Me.Controls.Remove(NowButton) '删除按键
NowButton.Dispose() '销毁
End Sub