Why controls do not want to get removed?

You have to watch out for code like this, removing controls from their container like this produces an unrecoverable resource leak. Controls.Remove/At(), or the Controls.Clear() method as suggested by other posters, removes the control from the collection and re-hosts it to the “parking window”. An otherwise invisible window where the native window can find a hospitable home without having to be destroyed. Ready to be re-hosted on another parent.

Which is the trap, you typically don’t move it to another parent. The control will continue to survive on the parking window, consuming native Windows resources. The garbage collector cannot recover these resources. Eventually your program will crash when Windows refuses to provide more windows to your process. The exception message will say “Error creating handle”.

Instead, you must dispose the control. Which also automatically removes the control from its parent. The proper code is:

 while (contentsPanel.Controls.Count > 0) contentsPanel.Controls[0].Dispose();

Or iterate backwards if you find this a bit too bizarre looking.

Leave a Comment