遍历控件找不到 TextBox 控件

Looping Through Controls Doesn't Find TextBox Controls

你能解释一下为什么这不起作用吗?

    int count = 0;
    foreach (Control c in this.Controls)
    {
        if (c is TextBox)
        {
            TextBox textBox = c as TextBox;
            if (textBox.BackColor == Color.Green)
            {
                count++;

            }
        }
    }
    if (count == 40)
    {
        SchemaForm ff = new SchemaForm();
        ff.Show();
        this.Hide();
    }

}

这是一个测试,在检查完所有数据后,我需要将学生重定向到另一个页面。所以,我必须检查,如果所有文本框都有 green.BackColor 并且如果所有文本框都是,那么我们将转到另一页。

我认为问题出在这个 if 语句中:

if (c is TextBox)
        {
            TextBox textBox = c as TextBox;
            if (textBox.BackColor == Color.Green)
            {
                count++;

            }
        }

您可能想检查它的类型是否正确,如果是:

if (typeof(TextBox) == c.GetType()) {
        TextBox textBox = c as TextBox;
        if (textBox.BackColor == Color.Green)
        {
            count++;

        }
}

您的代码是正确的。可能缺少 TextBox 没有 Green 颜色,或者可能是您计算错误。

编辑:

正如您所解释的,所有 TextBoxes 都包含在 GroupBoxes 中,因此您必须遍历所有 groupBoxes

bool IsAllGreen = true;
foreach (GroupBox groupBox in this.Controls.OfType<GroupBox>()) //get all GroupBoxes
{
    foreach (TextBox textBox in groupBox.Controls.OfType<TextBox>()) //Get all Textboxes for every GroupBox
    {
        if (textBox.BackColor != Color.Green)   //if any textbox is not Green, it will not go further
        {
            IsAllGreen = false;
            break;
        }
    }
}
if (IsAllGreen)
{
    SchemaForm ff = new SchemaForm();
    ff.Show();
    this.Hide();
}