I have a user control that I’m adding at runtime to a panel. There is an add button to keep adding the same user control to the panel. My question is what is the best way to clear the user controls out (properly disposing of them) when you save the form or clear the form? I want to delete all additional user controls that were added from the add button and clear the first one.
Share
The Control.ControlCollection.Remove method will do the trick. Run this on your user controls’ container.
For example, if your user control’s Type is
YourUserControlTypeand the container from which you want to remove all instances of your user control is a Panel calledpanel1, this code should work:EDIT: for .NET 2.0+
Notice in both versions we’re avoiding removing controls from the controls collection as we’re iterating through that collection. Unless you’re careful, removing items from the collection as you’re iterating through can causes problems.