问题
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)?
回答1:
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.
回答2:
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);
}
来源:https://stackoverflow.com/questions/12808943/how-can-i-get-all-labels-on-a-form-and-set-the-text-property-of-those-with-a-par