Add the following class to your project.
public static class ControlExtensions
{
public static IEnumerable<T> Descendants<T>(this Control control) where T : class
{
foreach (Control child in control.Controls)
{
if (child is T thisControl)
{
yield return (T)thisControl;
}
if (child.HasChildren)
{
foreach (T descendant in Descendants<T>(child))
{
yield return descendant;
}
}
}
}
public static List<TextBox> TextBoxList(this Control control)
=> control.Descendants<TextBox>().ToList();
}
Usage in a form.
Example 1:
Are there any empty TextBox controls on the form or in say a panel or group box?
string[] textBoxes = this.TextBoxList()
.Where(tb => string.IsNullOrWhiteSpace(tb.Text))
.Select(tb => tb.Name)
.ToArray();
Example 2:
Get all TextBoxes and iterate
TextBox[] textBoxes = this.TextBoxList().ToArray();
foreach (var textBox in textBoxes)
{
// do validation
}
A better idea
Is to use Data Annotations but not getting into that here as it requires more of an effort and experience with C#.