Dynamically removing Lables Windows forms

  • Thread starter Thread starter Guest
  • Start date Start date
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
 
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/ .
 
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();
}
 
Back
Top