开发者

Trying to create text boxes dynammically and remove them

I am using VB.NET vb 2008 . I am trying to create text boxes dynammically and remove them here is the code i have written so far

 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

I am able to create the textboxes but only a few of them are removed. by using For Each ctrl In Panel1.Controls it doesn't retrieve all the controls and some ae duplicated as well.


Change your remove to

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

If I am not mistaken you should not change a collection in a loop that you are currently looping, using a for each. The safest ways would be to use the index, in reverse, so that the position is not affected.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜