Find multiple controls with by partially matching

2019-02-25 18:10发布

问题:

I currently have 100+ labels, with names like:

labelNumber1 
labelNumber2 
labelNumber3 
labelNumber4 
....
labelLetter1
labelLetter2 
labelLetter3 
labelLetter4
....

How would I find all the labels that have "Number" in the controls name? Instead of having to type out labelNumber1.text = "hello", etc.

I have tried regex and foreach with wild cards but did not succeed. I have looked on msdn.microsoft.com about using regex with a control.

回答1:

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.
    }
}


回答2:

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);
                }
            }
        }


回答3:

I know this is an old question, but I am here now, and:

  • The question asks about searching for multiple controls. This solution actually applies to any type of control.
  • OP was conflicted between using "Contains" or regex. I vote for regex! string.Contains is a bad idea for this kind of filter, since "CoolButton" has a "Button" in it too"

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+&");