My Thoughts & Views

Dynamically removing dynamically added controls

Posted on: April 11, 2007

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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: