How can I get all Labels on a form and set the Text property of those with a particular name pattern to string.empty?

人盡茶涼 提交于 2019-12-24 01:23:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!