尝试动态创建文本框并删除它们

时间:2010-04-03 07:11:15

标签: vb.net textbox

我正在使用VB.NET vb 2008 。我试图动态地创建文本框,并在这里删除它们是我到目前为止编写的代码

 Private Sub setTextBox()
        Dim num As Integer
        Dim pos As Integer

        num = Len(word)
        temp = String.Copy(word)
        Dim intcount As Integer





        remove()
        GuessBox.Visible = True
        letters.Visible = True



        pos = 0
        'To create the dynamic text box and add the controls 
        For intcount = 0 To num - 1
            Txtdynamic = New TextBox
            Txtdynamic.Width = 20
            Txtdynamic.Visible = True
            Txtdynamic.MaxLength = 1
            Txtdynamic.Location = New Point(pos + 5, 0)
            pos = pos + 30
            'set the font size
            Txtdynamic.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
            Txtdynamic.Name = "txtdynamic_" & intcount & "_mycntrl"
            Txtdynamic.Enabled = False
            Txtdynamic.Text = ""

            Panel1.Controls.Add(Txtdynamic)

        Next
        Panel1.Visible = True
        Controls.Add(Panel1)
        Controls.Add(GuessBox)
        Controls.Add(letters)
        letter = ""
        letters.Text = ""
        hang_lable.Text = ""

        tries = 0
    End Sub`enter code here`  



 Function remove()


            For Each ctrl In Panel1.Controls

            Panel1.Controls.Remove(ctrl)

        Next
    End Function

我可以创建文本框,但只删除了其中的一些。通过使用For Each ctrl在Panel1.Controls中,它不会检索所有控件,也会复制一些ae。

1 个答案:

答案 0 :(得分:0)

将您的删除更改为

Sub remove()
    For i As Integer = Panel1.Controls.Count - 1 To 0 Step -1
        Panel1.Controls.Remove(Panel1.Controls(i))
    Next i
End Sub

如果我没弄错的话,你不应该在你正在循环的循环中更改一个集合,使用for each。最安全的方法是反过来使用索引,这样位置就不会受到影响。