Visual Basic Dynamically Create and Erase Controls

时间:2015-07-28 16:05:12

标签: vb.net visual-studio visual-studio-2015

I use Visual Basic in Visual Studio 2015 and i am trying when i click on a StripMenu to appear me some TextBoxes and Buttons. After another click in Stripmenu i want to erase them and add new one. My problem is in Erase (delete or clear my buttons and textboxes) controls from my surface. I try to do it use Button.Visible =True (or False) but it's not seems to be really helpful in a big amount of controls.

Private Sub ClassAToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ClassAToolStripMenuItem.Click
    Label1.Text = "Sum A class Students: "

    Dim btnA As Button = New Button
    btnA.Location = New Point(420, 180)
    btnA.Name = "Btn1"
    btnA.Text = "OK"
    btnA.Visible = True
    Me.Controls.Add(btnA)
    AddHandler btnA.Click, AddressOf button
End Sub

Private Sub button()
    'What my Button does.
End Sub

I create dynamically through this code my Button but if i want to go in another Menu option i want to erase this button to add again my new controls (such us new buttons labels etc).

2 个答案:

答案 0 :(得分:1)

您的声明超出了范围,因为您在菜单的click方法中声明了它。您必须使用Find方法取回对您创建的控件的引用:

Dim btn = Me.Controls.Find("Btn1", True).FirstOrDefault()
If btn IsNot Nothing Then
  btn.Dispose()
End If

如果您尝试使用菜单上的新“屏幕”替换面板内容,可以尝试使用以下代码:

While Panel1.Controls.Count > 0
  Panel1.Controls(0).Dispose()
End While

Dim newControl As New UserControl1
newControl.Dock = DockStyle.Fill
Panel1.Controls.Add(newControl)

答案 1 :(得分:0)

在表单上添加面板然后将控件添加到面板会更容易 Panel.controls.clear() - 将删除面板上的控件