Find multiple controls with by partially matching their name

后端 未结 3 1076
别那么骄傲
别那么骄傲 2021-01-19 10:14

I currently have 100+ labels, with names like:

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


        
相关标签:
3条回答
  • 2021-01-19 10:52

    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.
        }
    }
    
    0 讨论(0)
  • 2021-01-19 11:17

    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);
                    }
                }
            }
    
    0 讨论(0)
  • 2021-01-19 11:17

    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+&");
    
    0 讨论(0)
提交回复
热议问题