a reflection question

A

Adam Right

Hi,

I want to write a code (by reflection ) to get the all button controls on a
mdi form. my sample code for that :

---------------------------------

FieldInfo[] fieldInfo = this.GetType().GetFields(BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.Public);

for (int i = 0; i < fieldInfo.Length; i++)

{

object obj = fieldInfo.GetValue(this);

string fieldName = fieldInfo.Name;

if (obj is System.Windows.Forms.Button)

{

// to do somthing

}

}

---------------------------------

It works for design-time controls.But, if i create button controls
dynamically in tun-time , i can not get these tun-time controls.
Do you have any idea to get controls that is added in run-time .. ?

Thanks.

Adam Right
 
M

Marc Gravell

Simple - don't use reflection ;-p

Instead, walk the Controls collection - something like the following
maybe (sorry, no VS at the moment - should be close, though)


private void ForAll<T>(Control parent, Action<T> action) where T :
Control {
foreach(Control child in parent.Controls) {
T t = child as T;
if(t!=null) action(t); // call the action for all of this type
ForAll<T>(child, action); // recurse
}
}
....
ForAll<Button>(this, delegate (Button b) {
b.Text = "Hi";
});
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top