我在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
此处名为dtba
和dtbc
的文本框被删除。但dtbb
和dtbd
不会被删除。有任何帮助吗?
答案 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有关,即在删除控件时丢失指针。您必须重复该操作以确保新索引。