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,738
  • 21
  • 105
  • 131
dario_ramos
  • 7,118
  • 9
  • 61
  • 108

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
  • 554,122
  • 78
  • 1,158
  • 1,373
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,738
  • 21
  • 105
  • 131
denied66
  • 644
  • 7
  • 18