Saturday, November 11, 2006

Using the Controls.Remove method

Whe interating through a form's control list, simply removing a control from it doesn't work (the subsequent controls are moved one position up when you try to remove one of them?). Thus, two foreach loops shoud be used :

// clear previous turtle buttons
ArrayList forRemoval = new ArrayList();

// find buttons to remove from the control list
foreach (Control c in this.Controls)
{
Button b = c as Button;
if (b == null || !b.Name.StartsWith("turtle")) continue;

forRemoval.Add(c);
}

foreach (object o in forRemoval)
{
Button b = o as Button;
if (b == null) continue;

this.Controls.Remove(b);
}

No comments: