动态文本框添加和处置:很少有文本框没有得到处置

Dynamic textbox add and dispose : Few text boxes not getting disposed

我在 windows 表单中动态创建了几个文本框,有时我 dispose 这些

        Dim tb1 As New TextBox          'new textbox
        tb1.Name = "dtba"               'setname
        tb1.Location = New Point(stx, sty)  'location of textbox
        tb1.Text = arl(0)                   'assigning text
        tb1.Width = 80                      'setting width
        tb1.TabStop = False                 'no tabstop
        tb1.Enabled = False                 'disabled
        Me.Controls.Add(tb1)                'add to form

'为更多的文本框重复相同的代码

            Dim tb2 As New TextBox
            tb2.Name = "dtbb"
            tb2.Location = New Point(stx + 80, sty)
            tb2.Text = arl(1)
            tb2.Width = 175
            tb2.TabStop = False
            tb2.Enabled = False
            Me.Controls.Add(tb2)
            Dim tb3 As New TextBox
            tb3.Name = "dtbc"
            tb3.Location = New Point(stx + 255, sty)
            tb3.Text = arl(2)
            tb3.Width = 125
            tb3.TabStop = False
            tb3.Enabled = False
            Me.Controls.Add(tb3)
            Dim tb4 As New TextBox
            tb4.Name = "dtbd"
            tb4.Location = New Point(stx + 380, sty)
            tb4.Text = arl(3)
            tb4.Width = 100
            tb4.TabStop = False
            tb4.Enabled = False
            Me.Controls.Add(tb4)

当我尝试删除这些文本框时出现问题。代码是

        For Each cControl In Me.Controls
            If (TypeOf cControl Is TextBox) Then
                Dim txt As TextBox = CType(cControl, TextBox)
                If txt.Name.Contains("dtb") Then
                    txt.Dispose()
                End If
            End If
        Next cControl

此处名为 dtbadtbc 的文本框将被删除。但是 dtbbdtbd 没有被删除。 有帮助吗?

您正在循环编辑 collection。尝试这样的事情:

    Dim l As New List(Of Control)

    For Each cControl In Me.Controls
        If (TypeOf cControl Is TextBox) Then
            Dim txt As TextBox = CType(cControl, TextBox)
            If txt.Name.Contains("dtb") Then
                l.Add(cControl)
            End If
        End If
    Next cControl

    For Each c As Control In l
        c.Dispose()
    Next

而是利用这个:

    For Each cControl In Me.Controls
        If (TypeOf cControl Is TextBox) Then
            Dim txt As TextBox = CType(cControl, TextBox)
            If txt.Name.Contains("dtb") Then
                txt.Dispose()
            End If
        End If
    Next cControl

这样做:

    Again:
    For Each cControl In Me.Controls
        If (TypeOf cControl Is TextBox) Then
            Dim txt As TextBox = CType(cControl, TextBox)
            If txt.Name.Contains("dtb") Then
                Me.Controls.Remove(txt)
                GoTo again
            End If
        End If
    Next

这个问题与 FOR EACH 的 INDEX 有关,删除控件时会丢失指针。必须重复操作才能保证有新的索引。