CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    May 2013
    Posts
    1

    Removing Controls from form

    Hello everyone,

    First of all, i'm new to C#. I've bought a book to learn the basics and now i'm trying to write a little program.

    I'm having problems with removing controls from a form.

    Small explanation of the program i'm writing.

    I search a folder every 30 seconds to see what files there are inside.

    When i find files, i create a label (to display the name) and a button (to open the file). Every time i refresh, i need to clear the existin labels and buttons so they don't mixup.

    I do this using a foreach loop:

    foreach (Control c in test2.Controls)
    {
    if (c.Name.Contains("DYNAMIC") == true)
    {

    test2.Controls.Remove(c);
    }
    }

    I set the name of the label to DYNAMIC_LBL(index) and the buttons to DYNAMIC_BTN(index).

    Sometimes it works, sometimes it only deletes the buttons....

    Does anyone know what i am doing wrong??

    Screenshots below
    Name:  firstrefresh.png
Views: 431
Size:  55.8 KBName:  secondrefresh.png
Views: 400
Size:  43.2 KB

    Greetings and thanks,

    Nico

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: Removing Controls from form

    Use a Panel control and add the controls as children of the panel. When you need to clear the controls, just remove all the controls inside the panel:
    Code:
    _panel.Controls.Clear();

  3. #3
    Join Date
    Jan 2010
    Posts
    1,133

    Re: Removing Controls from form

    Another important thing - when using foreach, never modify the collection you are iterating over! By "modify" I mean alter the structure of the collection itself (like add/remove items) - it is OK to change the state of the elements contained within the collection, but the collection itself should not change.
    For example, if you are removing elements of the collection as you loop through them, strange thing can happen (like, some elements might be "skipped"), and in certain circumstances you might even cause your program to crash.
    If you a collection supports an indexer, you can remove items from it it by using a for loop and going backwards.

    All that said, it's probably the best that you organize your code so that you can remove all of those controls at once, as Arjay suggested.

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

Featured