c# - cannot loop oo components in a usercontrol -


i bit confused. implemented own usercontrol , want control discover components (like binding source) hosted in same control @ design time.

code this:

private void findcomponentbyname(string aname)   {      foreach(component component in this.container.components)      {         if (component.tostring()==aname)          {           dosomething();           break;            }      }   }   

this code not working either @ design time or run time container null.

if run code in form not in usercontrol

private component findcomponentbyname(string aname)           {               component result = null;               foreach (component component in this.components.components)               {                   if (component.tostring() == aname)                   {                       result = component;                       break;                   }               }               return result;           } 

it works, components not null , manage retrieve components.

i need @ run time , @ design-time too.

can please explain me what's mistake? , regards paolo

your code should this:

private void findcomponentbyname(string aname)   {       control c = findcomponentbyname(this);     if (c != null)     {         dosomething();     } }  private control findcomponentbyname(control c, string aname)   {    if (c.name == aname)    {        return c;    }     foreach(var control in c.controls)      {         //recurse containers controls make sure visit depths       control found = ctrl.findcomponentbyname(control, aname);       if (found != null)            return found;    }    return null; } 

you make extension method can call on whatever control need it:

public static class myextensions {     public static control findcontrolwithname(this control control, string aname)     {          if (control.name == aname)          {             return control;          }          foreach(var ctrl in control.controls)          {              control found = ctrl.findcontrolwithname(aname);              if (found != null)                  return found;          }          return null;     } } 

and can call like:

if (somecontrol.findcontrolwithname("hola") != null) {     dosomething(); } 

Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -