I have a Panel control. And inside the panel users can add combobox\'s, textbox\'s labels etc and drag them around and stuff, and there\'s a Delete button on my form where if th
I have seen this before, you are removing items from acollection that make the collection itself smaller. e.g if there are 5 items in the collection as you move down through it you come to the end of the list sooner than you expect because the list gets smaller with every Dispose() you issue.
I know is a pretty old post, but I hope could help somebody.
The only way I found that works is:
while(panel.Controls.Count > 0)
{
panel.Controls[0].Dispose();
}
This way it doesn't matter if the list of Controls become smaller in the middle of the loop.
Dispose()
only cleans up unmanaged resources (although Paul Williams noted in the comments that it is usually more complex than this!) so it may or may not do anything useful in your case.
Try removing the controls with the RemoveAt(i)
method, not Dispose()
:
for(int i = panel.Controls.Count-1; i >= 0; i--)
{
panel.Controls.RemoveAt(i);
}
A simpler way to delete all your controls is to do this:
panel.Controls.Clear();
Edit: thanks to Pieter and Paolo, just calling Clear() like this will leak memory since the controls are not disposed, so this is not a good practice.