Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/267.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么标签控件不是';如果标签在GroupBox中,是否在foreach循环中被击中?_C#_Winforms - Fatal编程技术网

C# 为什么标签控件不是';如果标签在GroupBox中,是否在foreach循环中被击中?

C# 为什么标签控件不是';如果标签在GroupBox中,是否在foreach循环中被击中?,c#,winforms,C#,Winforms,如果标签位于GroupBox中,则不会在foreach循环中命中标签控件。如果标签位于GroupBox之外,则它们位于GroupBox之外。如何让我的循环找到它们 foreach (Control c in this.Controls) { if (c is Label) { if (c.Text == "12/31/1600") { c.Text = "

如果标签位于GroupBox中,则不会在foreach循环中命中标签控件。如果标签位于GroupBox之外,则它们位于GroupBox之外。如何让我的循环找到它们

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


您可以使用递归。首先,定义接受控件作为参数的委托:

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

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

您可能应该将c转换为标签以检查文本属性。;)我不必费心铸造,因为我检查
c是标签
Oops。。。我没有意识到控件有文本属性,我在考虑WebForms。我的错。哈哈。谢谢,杰里米。这件事让我很困惑。我想他想把标签都放进和放出来。如果有更多的分组框呢?
public delegate void DoSomethingWithControl(Control c);
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);