0

I am trying to iterate through the textboxes in my window so I can make operations on them. Here is my code:

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

I have put a breakpoint on the line with if, my program reaches that breakpoint, but it doesn't reach the MessageBox line... Where is the error? (I tested this with c is Button and it worked...)

Cœur
  • 37,241
  • 25
  • 195
  • 267
Victor
  • 13,914
  • 19
  • 78
  • 147

2 Answers2

3

It's fairly so simple that I don't want to add an answer, but for the OP's request:

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.
King King
  • 61,710
  • 16
  • 105
  • 130
1

This should help you

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

Alternative :

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