Results 1 to 4 of 4

Thread: [RESOLVED] Removing controls

  1. #1

    Thread Starter
    Fanatic Member Arve K.'s Avatar
    Join Date
    Sep 2008
    Location
    Kyrksæterøra, Norway
    Posts
    518

    Resolved [RESOLVED] Removing controls

    Hi,

    I'm using this code to remove controls from a panel...
    vb.net Code:
    1. For Each c As Control In Me.pnlDevices.Controls
    2.     Me.pnlDevices.Controls.Remove(c)
    3. Next
    ...but somehow it doesn't remove all the controls at once, I have to run the code 3 times to remove them all
    (there is about 20 to 30 of them, mainly labels)...

    I don't know if it matters, but the controls where added dynamically at startup...
    Last edited by Arve K.; Oct 6th, 2011 at 07:53 PM. Reason: typo + added some info
    Arve K.

    Please mark your thread as resolved and add reputation to those who helped you solve your problem
    Disclaimer: I am not a professional programmer

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: Removing controls

    I'm surprised that that code actually runs at all. I would have expected it to throw an exception. NEVER enumerate a list using a For each loop and then modify the list inside the loop. If you want to clear a list completely then, if it has one, call its Clear method. Otherwise, use a Do or While loop or else use a For loop and go from end to beginning rather than beginning to end.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,416

    Re: Removing controls

    try this instead:

    vb Code:
    1. For x As Integer = Me.pnlDevices.Controls.count - 1 To 0 Step -1
    2.     Me.pnlDevices.Controls.RemoveAt(x)
    3. Next

    your code modifies Me.pnlDevices.Controls in a for each loop causing the for each to fail.

  4. #4

    Thread Starter
    Fanatic Member Arve K.'s Avatar
    Join Date
    Sep 2008
    Location
    Kyrksæterøra, Norway
    Posts
    518

    Re: Removing controls

    Oh, I never thought of it that way... No wonder it didn't work

    Thank you both for you help, problem solved!
    Arve K.

    Please mark your thread as resolved and add reputation to those who helped you solve your problem
    Disclaimer: I am not a professional programmer

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width