a reflection question

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Adam Right

    #1

    a reflection question

    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(Bindi ngFlags.NonPubl ic |
    BindingFlags.In stance | BindingFlags.Pu blic);

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

    {

    object obj = fieldInfo[i].GetValue(this) ;

    string fieldName = fieldInfo[i].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




  • Marc Gravell

    #2
    Re: a reflection question

    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>(Contr ol parent, Action<Taction) 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";
    });

    Comment

    Working...