2

I want to clear all values on a form where the control is a label and its name starts with "label"

This code:

List<Label> lbls = this.Controls.OfType<Label>().ToList();
foreach (var lbl in lbls)
{
    if (lbl.Name.StartsWith("label"))
    {
        lbl.Text = string.Empty;
    }
}

...doesn't work, because the lambda is finding nothing - lbls.Count = 0.

Wouldn't this get ALL the controls on the form, even those that are children of other controls (such as, in my case, Panels)?

B. Clay Shannon-B. Crow Raven
  • 8,547
  • 144
  • 472
  • 862
  • No, it does only find controls in the parent container. But i assume that you know what you want to find. So you just have to specify the container(s) you want to search. You can use `Concat` to add all labels. – Tim Schmelter Oct 09 '12 at 21:51
  • I don't think this will search all the containers recursively – Sushanth -- Oct 09 '12 at 21:51
  • No, this.Controls contains only the first level of controls. Those directly hosted on the Form surface. – Steve Oct 09 '12 at 21:53

3 Answers3

8

Try to use this method:

public void ClearLabel(Control control)
{
   if (control is Label)
   {
       Label lbl = (Label)control;
       if (lbl.Text.StartsWith("label"))
           lbl.Text = String.Empty;

   }
   else
       foreach (Control child in control.Controls)
       {
           ClearLabel(child);
       }

}

You just need to pass form to ClearLabel method.

Danilo Vulović
  • 2,983
  • 20
  • 31
4

No, it will not recursively search Panels.

To do what you want, you can do:

void changeLabel(Control c)
{
    if (lbl.Name.StartsWith("label"))
    {
        lbl.Text = string.Empty;
    }

    foreach(Control _c in c.Controls)
        changeLabel(_c);
}
CrazyCasta
  • 26,917
  • 4
  • 45
  • 72
1

This does not touch the matter of recursion brought up in the previous answers; it's just another, a little more succint way of expressing what you had:

var labels = Controls.OfType<Label>().Where( x => x.Name.StartsWith("label") );
foreach (var label in labels)
{
    label.Text = "";
}

That's what I ended up writing, I thought of adding it here just for completeness - essentially, you don't need ToList(), and String.Empty hasn't had any advantage over "" for ages.

Marc.2377
  • 7,807
  • 7
  • 51
  • 95