动态文本框添加和配置:几个文本框没有被丢弃

时间:2015-11-18 12:08:05

标签: vb.net visual-studio-2010 windows-forms-designer

我在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不会被删除。有任何帮助吗?

2 个答案:

答案 0 :(得分:1)

您正在编辑集合,同时循环它。尝试这样的事情:

    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

答案 1 :(得分:0)

取而代之的是:

    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有关,即在删除控件时丢失指针。您必须重复该操作以确保新索引。