Reputation: 149
After this "foreach" done, there is still buttons into panelGroups.Controls
foreach (Button button in panelGroups.Controls)
{
panelGroups.Controls.Remove(button);
}
Debug mode in Visual Studio:
Upvotes: 0
Views: 81
Reputation: 43876
The code you show is very error prone:
If there is a Control
in your panelGroups.Controls
that is no Button
and not inherited from Button
, your code will throw an InvalidCastException
. That is because you try to cast every Control
in that panel into a Button
, which will fail for example for a Label
You try to change an enumeration (by calling Remove
) while you are iterating through it. This causes an InvalidOperationException
.
You better try it that way:
foreach(Button button in panelGroups.Controls.OfType<Button>().ToList())
panelGroups.Controls.Remove(button);
By using OfType<Button>()
you select only the controls from the panel that really are Button
.
By calling ToList()
you complete that iteration to select the buttons from Controls
before starting the iteration over the resulting Button
set.
This way you would avoid the exceptions and your code should work.
Note however that this only works for Button
s that are directly contained in your panelGroups
. If you have other containers (like panels or groupboxes) inside that panel that contain more buttons, these buttons are not enumerated this way. You would have to recurse down through the containers and remove these buttons from the containers' Controls
collection.
Upvotes: 1