我不能遍历文本框

时间:2013-08-04 15:22:59

标签: c# .net winforms

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

foreach (Control c in Controls)
{
    if (c is System.Windows.Forms.TextBox)
    {
        MessageBox.Show(c.Name);
    }
}

我在if的行上放了一个断点,我的程序到达那个断点,但它没有到达MessageBox行......错误在哪里? (我用c is Button对此进行了测试,并且有效...)

2 个答案:

答案 0 :(得分:3)

这很简单,我不想添加答案,但是对于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.

答案 1 :(得分:1)

这应该可以帮到你

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

替代方案:

void TextBoxesName(Control parent)
{
    foreach (Control child in parent.Controls)
    {
        TextBox textBox = child as TextBox;
        if (textBox == null)
            ClearTextBoxes(child);
        else
            MessageBox.Show(textbox.Name);
    }
}

    TextBoxesName(this);