1

I would like to add a dynamic CheckAll() method to check all checkboxes declared in my class.

I tried following code:

class MyContol : UserControl
{
  ///
  ///  HIDDEN but there is plenty of checkboxes declaration
  ///

  private void CheckAll()
  {
    FieldInfo[] props = this.GetType().GetFields();

    foreach (FieldInfo p in props)
    {
      if (p.FieldType is CheckBox)
      {
         /// TODO: Check my box
      }
    }
  }
}

... but props is empty. I have no idea how to target checkboxes made with designer part.

Do you know using Reflection how to target added by design view components?

mickro
  • 881
  • 2
  • 11
  • 26

2 Answers2

2

The checkboxes of the control should all be child controls. That is, they are children (or possibly children of children) in the Control.Controls collection. Furthermore, controls do not have to have a reference to them as a property or field of the class. For example, I can add a checkbox to an existing control with myControl.Controls.Add(new CheckBox()). Therefore you do not need reflection here, nor will it really get you what you want - if I'm understanding you correctly.

Try enumerating them this way (to check for example controls in a panel you will need to do the recursive search):

private void CheckAll(Control parent)
{
    foreach(Control c in parent.Controls)
    {
        if (c is CheckBox)
            Check((CheckBox)c);

        CheckAll(c);
    }
}

private void CheckAll()
{
    CheckAll(this);
}
lc.
  • 113,939
  • 20
  • 158
  • 187
1

By default controls on your UserControl are private fields so I guess you should provide NonPublic flag as the parameter for binding attributes in GetFields method try this:

this.GetType().GetFields(System.Reflection.BindingFlags.NonPublic);

but you don't need reflection to achieve what you're looking for here.

VahidNaderi
  • 2,448
  • 1
  • 23
  • 35
  • I see but finally I prefer solution introduced by *lc.* which is as you said without `Reflection` – mickro Sep 09 '13 at 20:00