I designed a windows form which has textbox1
placed on the Form directly and textbox2
on the goupbox1
. Running below code only changes text of textbox1
. I googled a lot but I could not find the solution. How can i reach textbox2
?
public Form1()
{
InitializeComponent();
foreach (TextBox txtBox in this.Controls.OfType<TextBox>())
{
txtBox.Enter += textBox_Enter;
txtBox.Text = "123"; //To test if the text box is recognized or not
}
}
You can use recursion.
I'd recommend you to use the following extension method:
public static IEnumerable<T> GetAllControls<T>(Control control)
{
var controls = control.Controls.OfType<T>();
return control.Controls.Cast<Control>()
.Aggregate(controls, (current, c) => current.Concat(GetAllControls<T>(c)));
}
Usage:
var textBoxes = GetAllControls<TextBox>(this);