Remove custom controls [RESOLVED]
hey im trying to remove all my custom controls from my form, but not all of the are removed. i have to call my lear function a few times, depending on the number of controls. All of the controls are created at runtime and have different names.
Code:
private void ClearResults()
{
foreach(Control c in this.pMain.Controls)
{
if(c is ResultsItem)
{
#if DEBUG
Debug.WriteLine("Disposing of " + c.Name.ToString());
#endif
c.Visible = false;
c.Dispose();
}
}
}
Is there a better way to remove the controls from a form?
Thanks
Re: Remove custom controls
The issue you're running into is that you're altering the collection that you're enumerating, instead try something like this:
Code:
private void btnAddControls_Click(object sender, System.EventArgs e)
{
int count = new Random(DateTime.Now.TimeOfDay.Seconds).Next(49) + 1;
this.pnlContainer.SuspendLayout();
for( int i=0; i<count; i++ )
{
myControl control = new myControl();
control.Name = "myControl" + i.ToString();
control.Location = new Point((i % 4) * control.Width, (i / 4) * control.Height);
this.pnlContainer.Controls.Add(control);
}
this.pnlContainer.ResumeLayout();
}
private void btnClearControls_Click(object sender, System.EventArgs e)
{
this.pnlContainer.SuspendLayout();
for( int i=0; i<this.pnlContainer.Controls.Count; i++ )
if( this.pnlContainer.Controls[i] is myControl )
{
myControl control = (myControl)this.pnlContainer.Controls[i];
this.pnlContainer.Controls.RemoveAt(i);
control.Dispose();
i--;
}
this.pnlContainer.ResumeLayout();
}
Re: Remove custom controls
cheers working great now. Thanks :)