ASP.NET Is there a better way to find controls that are within other controls?
Asked Answered
B

2

1

I currently have a dropdown inside an ascx control. I need to "find" it from within the code behind on another ascx that is on the same page. It's value is used as a param to an ObjectDataSource on ascx #2. I am currently using this ugly piece of code. It works but I realize if the conrtol order were to change or various other things, it wouldn't be where I am expecting. Does anyone have any advice how I should properly be doing this?

if(Page is ClaimBase)
{
  var p = Page as ClaimBase;
  var controls = p.Controls[0].Controls[3].Controls[2].Controls[7].Controls[0];
  var ddl = controls.FindControl("ddCovCert") as DropDownList;
}

Thanks and Happy New Year!! ~ck in San Diego

Bestow answered 31/12, 2009 at 23:2 Comment(0)
C
6

Generally I implement a "FindInPage" or recursive FindControl function when you have lots of control finding to do, where you would just pass it a control and it would recursively descend the control tree.

If it's just a one-off thing, consider exposing the control you need in your API so you can access it directly.

public static Control DeepFindControl(Control c, string id)
{
   if (c.ID == id)
   { 
     return c;
   }
   if (c.HasControls)
   {
      Control temp;
      foreach (var subcontrol in c.Controls)
      {
          temp = DeepFindControl(subcontrol, id);
          if (temp != null)
          {
              return temp; 
          }
      }
   }
   return null;
}
Caeoma answered 31/12, 2009 at 23:6 Comment(1)
sweet. I use this alot and it works pretty well. A simple solution.Bestow
S
6

Expose a property on the user control class which will return the value you need. Let the page access the property.

Only the user control should know what controls are inside of it.

Succinctorium answered 31/12, 2009 at 23:4 Comment(0)
C
6

Generally I implement a "FindInPage" or recursive FindControl function when you have lots of control finding to do, where you would just pass it a control and it would recursively descend the control tree.

If it's just a one-off thing, consider exposing the control you need in your API so you can access it directly.

public static Control DeepFindControl(Control c, string id)
{
   if (c.ID == id)
   { 
     return c;
   }
   if (c.HasControls)
   {
      Control temp;
      foreach (var subcontrol in c.Controls)
      {
          temp = DeepFindControl(subcontrol, id);
          if (temp != null)
          {
              return temp; 
          }
      }
   }
   return null;
}
Caeoma answered 31/12, 2009 at 23:6 Comment(1)
sweet. I use this alot and it works pretty well. A simple solution.Bestow

© 2022 - 2024 — McMap. All rights reserved.