I currently have 100+ labels, with names like:
labelNumber1
labelNumber2
labelNumber3
labelNumber4
....
labelLetter1
labelLetter2
labelLetter3
labelLet
You can loop through the Controls collection of the form and just check the name of each control that it contains something like 'Label'. or you could check that the control is a typeof TextBox, Label, etc.
E.g.
foreach (Control control in form.Controls)
{
if (control.Name.ToUpper().Contains("[Your control search string here]"))
{
// Do something here.
}
if (control is TextBox) {
// Do something here.
}
}
you can filter the list of controls to only return the labels. You would also want to make sure the name is greater than 11 chars.
List<Label> allNumberLabels = new List<Label>();
foreach (Label t in this.Controls.OfType<Label>())
{
if (t.Name.Length > 11)
{
if (t.Name.Substring(5, 6).Equals("Number"))
{
allNumberLabels.Add(t);
}
}
}
I know this is an old question, but I am here now, and:
Anyway, here is the code:
public List<TControlType> FindByPattern<TControlType>(string regexPattern)
where TControlType:Control
{
return Controls.OfType<TControlType>()
.Where(control => Regex.IsMatch(control.Name, regexPattern))
.ToList();
}
Usage:
//some regex samples you can test out
var startsWithLabel = $"^Label"; //Matches like .StartsWith()
var containsLabel = "Label"; //Matches like .Contains()
var startsWithLabelEndsWithNumber = "^Label.*\\d+&"; //matches Label8sdf12 and Label8
var containsLabelEndsWithNumber = "Label.*\\d+&"; //matches MyLabelRocks83475, MyLabel8Rocks54389, MyLabel8, Label8
var hasAnyNumber= "^CoolLabel\\d+$"; //matches CoolLabel437627
var labels = FindByPattern<Label>("^MyCoolLabel.*\\d+&");
var buttons = FindByPattern<Button("^AveragelyCoolButton.*\\d+&");