panel question

im tring to remove controls from a panel

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

Dim ctrl As Control

For Each ctrl In Me.Panel1.Controls

Me.Panel1.Controls.Remove(ctrl)

Next ctrl

End Sub

this only removes half the controls. what am i missing

Thanks,

dan



Answer this question

panel question

  • llebron

    The problem is that on each itteration of the loop there is one less control in the collection. Since the collection is constantly shrinking, the previous item no longer exists which is causing the loop to effectively only see every other control.

    Try this code instead:

    For i As Integer = Panel1.Controls.Count - 1 To 0 Step -1

    Panel1.Controls.RemoveAt(i)

    Next

    Using a reverse loop is the proper to perform a loop over a collection that reduces the size of that collection.

    HTH, GL!



  • Jim Selinsky

    I only want to remove some of the controls on the panel...

    i have a button to insert that expands the panel and puts in some controls

    i'm creating one to delete that set of controls that was inserted if the user decides they dont want them...if i keep clicking remove i eventually clear the panel but that doesnt seem right...

    thanks,

    Dan


  • gmork

    Not sure why, but you could always just say Me.Panel1.Controls.Clear().

    Hope that helps,

    Jonathan Aneja

    The VB Team



  • MichaelLaw

    thats it! Thanks!

    Dan


  • panel question