-
May 3rd, 2013, 08:35 AM
#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
Greetings and thanks,
Nico
-
May 3rd, 2013, 01:30 PM
#2
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();
-
May 6th, 2013, 05:13 PM
#3
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|