Wednesday, April 11, 2007

Dynamically removing dynamically added controls

I dynamically add controls to my form, and also i need the option to remove them again.So first i did this to remove,(as per my logic)

foreach(Control contrl in this.Controls)
{
if (contrl .GetType() == typeof(TextBox))
{
this.Controls.Remove(contrl );
}
}

But this code removed only alternative textboxes. At first i was unable to find it out,but then after searching on net i found that when you remove a control from the ControlCollection, subsequent controls are moved up to fill that space. And found the solution to my problem. The code that must be used is like below.

foreach (Control contrl in this.Controls)
{
if (contrl.GetType() == typeof(TextBox))
{
ContrlToRemove.Add((TextBox)contrl);
}
}

foreach (TextBox txtbox in ContrlToRemove)
this.Controls.Remove(txtBox);

Other Alternatives:
1. You can do it in a single loop when removing items from any sort of indexed container,it is always best to remove them in reverse order starting at the end.And also when manually removing windows controls from a container,it is best to Dispose them at the same time. Otherwise you may have a memory leak.

If you find other alternatives too keep me informed.

No comments: