I suspect your Textbox
is actually within some other containers, like a Panel
.
Try to find your control using a recursive approach:
public static Control FindTargetTextbox(Control control, string targetName)
{
foreach (Control child in control.Controls)
{
if (child is TextBox && child.Name == targetName)
{
return child;
}
}
foreach (Control child in control.Controls)
{
Control target = FindTargetComponent(child);
if (target != null)
{
return target;
}
}
return null;
}
Bear in mind that your form is the biggest container, therefore you should pass it in as the starting point:
TextBox textBox = FindTargetTextbox(this, name);
Edit
As @mikeng mentioned in the comment, we are able to merge two foreach
into one like this:
public static Control FindTargetTextbox(Control control, string targetName)
{
foreach (Control child in control.Controls)
{
if (child is TextBox && child.Name == targetName)
{
return child;
}
Control target = FindTargetComponent(child);
if (target != null)
{
return target;
}
}
return null;
}
This is indeed another valid approach, but one should choose the most appropriate approach based on the real situation:
The first approach explores all controls in the same container before it goes deep into a child control of that container, which is a Breadth First Search, while the second approach focuses on nested controls one by one, i.e. it goes to next container only after it finishes processing all controls in the current container, which is a Depth First Search.