3

如果标签位于 GroupBox 中,则标签控件不会在 foreach 循环中被击中。如果标签在 GroupBox 之外,它们就是。我怎样才能让我的循环找到它们?

     foreach (Control c in this.Controls)
     {
         if (c is Label)
         {
             if (c.Text == "12/31/1600")
             {
                 c.Text = "Not Found";
             }
         }
     }
4

3 回答 3

4
SetLabels (this);

public void SetLabels(Control ctrl)
{
  foreach (Control c in ctrl.Controls)
     {
         SetLabels(c);
         if (c is Label)
         {
             if (c.Text == "12/31/1600")
             {
                 c.Text = "Not Found";
             }
         }
     }
}
于 2012-09-27T02:41:49.000 回答
2

利用

this.groupBox1.Controls

 foreach (Control c in this.groupBox1.Controls)
 {
     if (c is Label)
     {
         if (c.Text == "12/31/1600")
         {
             c.Text = "Not Found";
         }
     }
 }
于 2012-09-27T02:42:42.570 回答
1

您可以使用递归。首先定义一个接受 Control 作为参数的委托:

public delegate void DoSomethingWithControl(Control c);

然后实现一个方法,将此委托作为第一个参数,并将递归执行它的控件作为第二个参数。此方法首先执行委托,然后在控件的 Controls 集合上循环以递归调用自身。这是有效的,因为 Controls 在 Control 中定义,并为简单的控件(如标签)返回一个空集合:

public void RecursivelyDoOnControls(DoSomethingWithControl aDel, Control aCtrl)
{
    aDel(aCtrl);
    foreach (Control c in aCtrl.Controls)
    {
        RecursivelyDoOnControls(aDel, c);
    }
}

现在您可以将更改标签值的代码放入方法中,并通过委托在表单上调用它:

    private void SetLabel(Control c)
    {
        if (c is Label)
        {
            if (c.Text == "12/31/1600")
            {
                c.Text = "Not Found";
            }
        }
    }

RecursivelyDoOnControls(new DoSomethingWithControl(SetLabel), this);
于 2012-09-27T08:44:52.083 回答