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)?

4

3 回答 3

7

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.

于 2012-10-09T21:58:44.597 回答
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);
}
于 2012-10-09T21:54:24.073 回答
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.

于 2020-11-19T05:34:48.017 回答