
用 Controls.Remove(控件) 动态删除控件。注意:在VB中只能动态删除那些动态添加的控件;不允许删除在窗体设计器上布置的控件!
示例如下:
(1)创建一个VB工程
(2)在Form1上布置两个Command
(3)窗体代码
Option Explicit' 声明要被动态添加/删除的控件
Dim x As Label
'-----------------------------
' 动态添加一个Label控件
'-----------------------------
Private Sub Command1_Click()
If x Is Nothing Then
Set x = Controls.Add("VB.Label", "label1")
x.Move 150, 150
x.AutoSize = True
x.Caption = "这个是动态添加的标签"
x.Visible = True
End If
End Sub
'-----------------
' 动态删除控件
'-----------------
Private Sub Command2_Click()
If x Is Nothing Then Exit Sub
Controls.Remove x
Set x = Nothing
End Sub
Private Sub Form_Load()
Command1.Caption = "添加控件"
Command2.Caption = "删除控件"
End Sub
(4)运行
窗体启动
点击“添加控件”按钮
点击“删除控件”按钮
单击button1在panel上动态新建了多个label,现在想要点击选择某个动态新建的label,按button2,可以把这个label删掉在button1_Click事件中,创建label,代码:
Label lb1 = new Label()
lb1.Name = "panel"+j
lb1.BackColor = Color.Transparent
lb1.BorderStyle = BorderStyle.FixedSingle
Panel1.Controls.Add(lb1)
为这些label增加Click事件
Label lb1 = new Label()
lb1.Name = "panel"+j
lb1.BackColor = Color.Transparent
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)