Reputation: 458
i just want to know how to list all panel objects without using for each loop and to prevent recursive procedure..
Upvotes: 0
Views: 2160
Reputation: 13286
In C#:
form.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance).
Where(fi => fi.FieldType.Equals(typeof(Panel)))
I used reflection since you wrote you don't want recursive method, however not all panels in your form can be discovered like that. If you create your panels without define a class member (this could be done even in the designer), you won't get it with this method.
Recursive method:
Panel[] GetPanels(Control container)
{
List<Panel> panels = new List<Panel>();
foreach (Control child in container.Controls)
{
if (child is Panel)
panels.Add(child as Panel);
panels.AddRange(GetPanels(child));
}
return panels.ToArray();
}
EDIT: The above method is not optimized. It is creating too many lists and can't be used as "lazy". Here is another improved version:
IEnumerable<Panel> GetPanelsLazy(Control container)
{
foreach (Control child in container.Controls)
{
if (child is Panel)
yield return child as Panel;
foreach (var panel in GetPanelsLazy(child))
{
yield return panel;
}
}
}
Upvotes: 2