views:

573

answers:

2

I am attempting to write a 'User Control' in WinForms .NET (not ASP.NET). The control is relatively simple. It will contain a label, a button, and a DataGridView.

However, the control needs to be able to instantiate itself, i.e. when the user clicks the button (of the parent control) at least 1 nested (children) control of the same type will be displayed underneath (kind of like a Tree)

I am having no success writing such a recursive control using a 'User Control'. A StackOverflow Exception occurs when instantiating MyControl within it's own constructor.

Therefore, I am leaning towards using a 'Custom Control', hoping it can handle the instantiation of itself (maybe in the Paint event??). Alot more work has to go into a Custom Control however, so I don't want to go down this path if it's going to take forever. I am on a tight deadline.

Anybody done this using a Custom Control or have any solid ideas on how to create a recursive control?

By the way, this control would be used in a fairly finite number of recursive combinations, so maybe it would be better to create a separate control for each parent/children scenario? I am thinking that would result in at least 10 separate user controls.

thanks for your help

UPDATE (here is my initial attempt at a stop condition per your feedback, but this is still causing children to be created indefinitely) :


public partial class CustomX : UserControl
    {
        private IList _children = new List();

        public CustomX()
        {
            InitializeComponent();

            Recurse(0);

        }

        private void Recurse(int childCount)
        {
            if (childCount 
+2  A: 

The problem is probably that the child control also instantiates a child control. There has to be a stop condition or controls will be generated until the stack overflows.

This should work:

public partial class CustomX : UserControl
    {
        private IList _children = new List();

        public CustomX(int depth)
        {
            InitializeComponent();
            if(depth > 0)
            {
                CustomX child = new CustomX(depth-1);
                this.Controls.Add(child)
            }
        }
    }
Wouter
+2  A: 

You should have no problem doing this with a user control. It is more likely an issue with not terminating the recursion properly. It (might) be more readable to perform the control creation in just the topmost parent control rather than delegating that task into each constructor.

Can you post the code you have in your constructor?

DancesWithBamboo