2

I want to list all controls inside another control which have names starting with "btnOverlay". I can't use Controls.Find, because it needs an exact match. I believe I can use LINQ for this, but I'm not very experienced on that. Is it possible? How can I do it?

I'm using .NET 4.0.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
dario_ramos
  • 6,736
  • 8
  • 56
  • 107

2 Answers2

6

You could search for them with LINQ via:

var matches = control.Controls.Cast<Control>()
                     .Where(c => c.Name.StartsWith("btnOverlay"));

The Cast<T> call is required, as ControlCollection does not implement IEnumerable<T>, only IEnumerable. Also, this doesn't do a recursive search, but only searches the contained controls directly. If recursion is required, you'll likely need to refactor this into a method similar to this answer.

Community
  • 1
  • 1
Reed Copsey
  • 539,124
  • 75
  • 1,126
  • 1,354
1

Here's an alternative without using LINQ:

foreach (Control c in this.Controls)
{
    if (c.Name.StartsWith("btnOverlay"))
    {
        // Do something
    }
}

Feel free to rename this. with the control you want to use.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
denied66
  • 644
  • 7
  • 18