Dynamically removing Lables Windows forms

G

Guest

Hi,

I'm trying to dynamically remove labels from a windows form in csharp. I
have a foreach loop similar to :

foreach(Control c in this.Controls)
{
c.Dispose();
}

The code does not find any labels but works fine for othet controls. I'm
clearing the entire form (excluding menus) so there may be a better way to do
this. I do not know the name(s) of the lables as they are created dynamically.

Thanks in advance, O
 
P

per9000

Hi Olan,

I managed to hide them, change the text on them, but not to dispose
them.

// works fine
MessageBox.Show(this.Controls.Count.ToString());

foreach (Control c in this.Controls)
{
c.Hide();
c.Update();
}

this.Update();

// changed text
foreach (Control c in this.Controls)
{
c.Text = "abodaboo";
c.Update();
}

// only removed a button
foreach (Control c in this.Controls)
{
c.Dispose();
}

this.Update();

----

HTH,
Per

Home: http://www.pererikstrandberg.se/blog/ .
Optimization in .NET: http://tomopt.com/tomnet/ .
 
B

Bruce Wood

Hi,

I'm trying to dynamically remove labels from a windows form in csharp. I
have a foreach loop similar to :

foreach(Control c in this.Controls)
{
c.Dispose();

}

The code does not find any labels but works fine for othet controls. I'm
clearing the entire form (excluding menus) so there may be a better way to do
this. I do not know the name(s) of the lables as they are created dynamically.

Ignoring for a moment that I have no idea why anyone would want to do
what you want to do... and therefore suspect that your original
problem (whatever it is) is probably best solved in some other way....

List<Control> controlsToRemove = new List<Control>();
foreach (Control c in this.Controls)
{
if (c is Label)
{
controlsToRemove.Add(c);
}
}
foreach (Control remove in controlsToRemove)
{
this.Controls.Remove(remove);
remove.Dispose();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top