Click here to Skip to main content
16,020,313 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hello all,

Is it possible to add usercontrol inside the same usercontrol (nesting) upto any level. Like by using loadcontrol("a.ascx") etc. plz help..
Posted
Comments
Eduard Keilholz 8-Oct-13 9:13am    
Yes
CodeBlack 8-Oct-13 9:46am    
Why do you want to add nested controls ?
gauriv 9-Oct-13 3:26am    
its a project requirement...like to have expression which contains inner brackets..like a and (b or(c and (d oe e))) like this...any idea?
ZurdoDev 8-Oct-13 9:53am    
Yes. But at some point you may get stack overflow. Just try it first.

1 solution

Yes, but you may have to manage the process if you're overriding the render methods or if using a custom collection for the children.

You have to add the controls to the parents Controls collection otherwise the Init and Load events wont fire properly in the child controls.

C#
public List<control> MyChildren { get; set; }

public override void Load(object sender, EventArgs e)
{

  foreach(Control c in MyChildren)
    this.Controls.Add(c);

}
</control>


Then you can render out your children.

C#
public override void Render(HtmlWriter writer)
{

  writer.Write("<div>");

  foreach(Control c in MyChildren)
    c.Render(writer);

  writer.Write("</div>");

}


This approach allows you to maintain more complex control hierarchies than simple parent, child controls.

---------- Update ----------

The MyChildren property declaration works exactly the same way as doing this:

C#
private List<Control> _myChildren;

public List<Control> MyChildren
{
  get { return _myChildren; }
  set { _myChildren = value; }
} 


Although for a control collection you'd probably want to protect the value and ensure it's instantiated.

C#
private List<Control> _myChildren;

public List<Control> MyChildren
{
  get { return _myChildren ?? (_myChildren = new List<Control>()); }
}
 
Share this answer
 
v2
Comments
gauriv 9-Oct-13 1:02am    
hi..thanks for replying please explain me the line public List<control> MyChildren { get; set; }
what should be written in get set..sorry this may be a stupid question but pls can u elaborate your answer more..
Stephen Hewison 9-Oct-13 3:22am    
Nothing should be written in the get or set. Visual Studio allows you to define properties like that without having to worry about managing private variables. Although I'll update my answer with a couple of examples.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900