Search code examples
c#asp.netascx

C# LoadControl() (.ascx) and add into "this" rather than sub control


I'm good with Loading the control, using the LoadControl("~/vitrualPath"), so I have:

UserControl ctrl = (UserControl)LoadControl("~/controls/someControl.ascx");
this.Controls.Add(ctrl);
//plcCtrl.Controls.Add(ctrl);

The trouble is that I wish to then loop through all the controls in the usercontrol:

foreach (Label c in this.Controls.OfType<Label>())
{
  // It's a label for an input
  if (c.ID.Substring(0, 8) == "lblInput")
   {
     // Do some stuff with the control here
   }
}

However, the added controls aren't part of this, but part of ctrl

Is there a way I can add the contents of the loaded control to this or a way to loop through both this and ctrl in one hit?


Solution

  • If you simply want to loop through both top-level labels and labels in ctrl, try this.Controls.Concat(ctrl.Controls).OfType<Label>() in your foreach loop.

    You can also move your if into a LINQ Where call:

    .Where(l => l.ID.Substring(0, 8) == "lblInput")