Reputation: 707
In Delphi you can iterate through a forms components (not controls) like so:
for i := 0 to Form1.ComponentCount - 1 do begin
However in c# Winforms i tried the following:
foreach (var component in this.components.Components)
{
MessageBox.Show(component.ToString());
}
I couldn't find any examples on google on how to iterate through components. All i found was how to iterate through controls.
I want to list all controls and components on a form. For example if there are 2 buttons and 2 imagelists i want to list all 4 items.
Upvotes: 2
Views: 502
Reputation: 12059
This is not easy in c#
Also be very carefull when you use inherited forms.
Unlike Delphi the unvisual designer has no support for oop when it comes to the components collection, there is a new collection created for every form even for descendants !
I did it like this : (it will only list components not controls !)
IEnumerable<Component> EnumerateComponents()
{
return from field in GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
where typeof(Component).IsAssignableFrom(field.FieldType)
let component = (Component)field.GetValue(this)
where component != null
select component;
}
you can call it like this :
foreach (Component component in EnumerateComponents())
{
if (component is ImageList)
{
}
}
Upvotes: 2