C# 我无法遍历文本框

C# 我无法遍历文本框,c#,.net,winforms,C#,.net,Winforms,我正在尝试遍历窗口中的文本框,以便对它们进行操作。这是我的密码: foreach (Control c in Controls) { if (c is System.Windows.Forms.TextBox) { MessageBox.Show(c.Name); } } 我在带有if的行上放置了一个断点,我的程序到达了该断点,但它没有到达MessageBox行。。。错误在哪里?(我用c is按钮测试了它,它成功了…这应该对你有帮助 foreac

我正在尝试遍历窗口中的文本框,以便对它们进行操作。这是我的密码:

foreach (Control c in Controls)
{
    if (c is System.Windows.Forms.TextBox)
    {
        MessageBox.Show(c.Name);
    }
}
我在带有
if
的行上放置了一个断点,我的程序到达了该断点,但它没有到达
MessageBox
行。。。错误在哪里?(我用
c is按钮测试了它,它成功了…

这应该对你有帮助

    foreach (TextBox t in this.Controls.OfType<TextBox>())
    {
         MessageBox.Show(t.Name);
    }
这应该对你有帮助

    foreach (TextBox t in this.Controls.OfType<TextBox>())
    {
         MessageBox.Show(t.Name);
    }

这相当简单,我不想添加答案,但对于OP的请求:

private void CheckTextBoxesName(Control root){
    foreach(Control c in root.Controls){
        if(c is TextBox) MessageBox.Show(c.Name);
        CheckTextBoxesName(c);
    }
}
//in your form scope call this:
CheckTextBoxesName(this);
//out of your form scope:
CheckTextBoxesName(yourForm);
//Note that, if your form has a TabControl, it's a little particular to add more code, otherwise, it's almost OK with the code above.

这相当简单,我不想添加答案,但对于OP的请求:

private void CheckTextBoxesName(Control root){
    foreach(Control c in root.Controls){
        if(c is TextBox) MessageBox.Show(c.Name);
        CheckTextBoxesName(c);
    }
}
//in your form scope call this:
CheckTextBoxesName(this);
//out of your form scope:
CheckTextBoxesName(yourForm);
//Note that, if your form has a TabControl, it's a little particular to add more code, otherwise, it's almost OK with the code above.


您确定文本框是表单的直接子项吗?它们(例如)不在面板上?事实上,它们是面板的孩子。。。在这种情况下,我能做什么,因为我在这个窗口上也有很多面板…@Victor
递归方法
循环遍历表单上的所有控件是您所需要的。然后,您可以发布一个答案吗?@Victor也许下面的答案之一可以帮助您。您确定文本框是表单的直接子项吗?它们(例如)不在面板上?事实上,它们是面板的孩子。。。在这种情况下我能做什么,因为我在这个窗口上还有很多面板…@Victor
递归方法
循环遍历表单上的所有控件是你所需要的。那么,你能发布一个答案吗?@Victor也许下面的答案之一可以帮助你。在OP的情况下,第一个代码不能工作,我们只有一个使用递归方法的解决方案。@KingKing,如果你知道答案,请给出答案!第一个代码在OP的情况下无法工作,我们只有一个使用递归方法的解决方案。@KingKing,如果你知道答案,请发布一个答案!我知道怎么称呼它:p@Victor请看我的编辑,它很简单。@keyboardP:))一个幽默的投票者?我知道怎么称呼它:p@Victor看我的编辑,很简单。@keyboardP:))一个幽默的投票者?