如何删除动态创建的控件?

时间:2015-04-24 17:24:17

标签: vb.net loops dynamic controls

我在表格中添加了几个图片框:

代码顶部:

Private Flag As PictureBox

在form1_Load事件下:

Flag.Location = New Point(buttonX, buttonY)
                        Flag.BackColor = Color.Red
                        Flag.BorderStyle = BorderStyle.FixedSingle
                        Flag.Name = "Flag" & Pos
                        Me.TabPage1.Controls.Add(Flag)
                        Flag.BringToFront()

所以我最终得到了4个名为“Flag2”“Flag5”“Flag6”“Flag8”的图片盒。然后,我尝试将它们全部删除:

Dim con As Control
        For Each con In Me.TabPage1.Controls
            If con.Name.Contains("Flag") Then
                Me.TabPage1.Controls.Remove(con)
            End If
        Next

最终发生的事情并非所有图片框都被删除。如果我多次运行删除代码,它将全部删除它们,但我试图立即删除它们。我也尝试过:

Dim con As Control
        Dim i As Integer = 0
        While i < Me.TabPage1.Controls.Count
            con = Me.TabPage1.Controls(i)
            If con.Name.Contains("Flag") Then
                Me.TabPage1.Controls.Remove(con)
            End If
            i += 1
        End While

两个“删除代码”都以相同的顺序删除图片框(不按照顺序创建的顺序),而不是删除所有图片框。

1 个答案:

答案 0 :(得分:0)

试试这样:

'create the pbs to delete
Dim pbs = Me.TabPage1.Controls.OfType(Of PictureBox)().
             Where(Function(pb) pb.Name.Contains("Flag"))
'loop thru them
For Each pb In pbs
  Me.TabPage1.Controls.Remove(pb)
Next 

子:

Public Sub RemovePictureBoxes(tp As TabPage)
  'create the pbs to delete
  Dim pbs = tp.Controls.OfType(Of PictureBox)().
             Where(Function(pb) pb.Name.Contains("Flag"))
  'loop thru them
  For Each pb In pbs
    tp.Controls.Remove(pb)
  Next  
End Sub

用法:

RemovePictureBoxes(TabPage1)