c# - Iteration over dynamically added nested controls -
i have groupbox on winform. groupbox added in run time within first groupbox.
few picturebox controls added within second groupbox.
now iterate pictureboxes.
currently code is:
foreach (control gbfirst in this.controls) { groupbox firstgroupbox = gbfirst groupbox; //first groupbox if (firstgroupbox != null) { foreach (control gbsecond in firstgroupbox.controls) { groupbox secondgroupbox = gbsecond groupbox; //second groupbox if (secondgroupbox != null) { foreach (control item in secondgroupbox.controls) { var pb = item picturebox; // picturebox if (pb != null) { string pbtag = pb.tag.tostring(); string customtag = ipaddress + "onoff"; if (pb.tag.tostring() == ipaddress + "onoff") { methodinvoker action = delegate { pb.image = properties.resources.mobicheckeronpng16; }; pb.begininvoke(action); break; } } } } } } }
but, unlike above, think there may easy or smart way it.
is so?
a generic function use control type in container @ levels:
public static list<t> findcontrols<t>(control container, bool dig) t : control { list<t> retval = new list<t>(); foreach (control item in container.controls) { if (item t) retval.add((t)item); if (dig && item.controls.count > 0) retval.addrange(findcontrols<t>(item, dig)); } return retval; }
the dig variable controls whether or not iterate through child container controls. example if want find picturebox controls starting first groupbox (gbfirst), must call
findcontrols<picturebox>(gbfirst, true);
if set dig false, controls in input cotainer enumerated.
Comments
Post a Comment