How can I retrive all the textBox from Windows Form

  • Thread starter Thread starter Fox
  • Start date Start date
F

Fox

foreach (TextBox tb in this.Controls)
MessageBox.Show(tb.Name);
//Error Occur for non-textBox, i.e. Button

Thank
 
I may find the answer.

for (int i=0;i<this.Controls.Count;i++)
if
(this.Controls.GetType().ToString()=="System.Windows.Forms.TextBox")
this.Controls.Text = "OK";


Any better Method?
 
Hi Fox,

As Adrian said, use foreach Control and check for TextBox, but beware this
will only find top level TextBoxes, not TextBoxes inside GroupBoxes,
Panels, TabPages or other container controls. If you have container
controls you may need to do a recursive search.
 
Fox,
Remember that you may have to descend into subgroups doing this. If you
have a groupbox on a form the textboxes inside it will be in its' controls
collection not the overall form's Controls collecton.

This will work although it hasn't been optimized

ArrayList boxes = new ArrayList(5);
foreach (Control c in this.Controls)
{
foreach (TextBox tb in GetTextBoxControls(c))
{
boxes.Add(tb);
}
}

private ArrayList GetTextBoxControls(Control c)
{
ArrayList x = new ArrayList(1);
if (c.Controls.Count > 0)
{
foreach (Control c1 in c.Controls)
{
ArrayList y = GetTextBoxControls(c1);
foreach (TextBox tmp in y)
{
x.Add(tmp);
}
}
}
else
{
if (c is TextBox)
{
x.Add(c);
}
}
return x;
}

Ron Allen
 
Back
Top