R – create the child controls in CreateChildControls() on a CompositeControl

asp.netcomposite-controls

Ok so the obvious answer is, because the flow of a composite control demands my childcontrols to be created at a certain point in time. I got a problem i think other people must have had as well.

My control is a composite "container/collection" control. It will be fed with an object and based on that objects data it will create a number of childcontrols. So my control will render a header (always) and x-number of, say TextBox controls (based on the object it was fed with).

I'm creating my header in CreateChildControls() obviously, but i can't possibly create my TextBoxes there as well, because i don't know if the object (to base the TextBoxes on) has been fed yet? I thought of exposing a property/method to set/fed the object through, but i'm not sure when it will be called.

So what do i do? I mean i can't possibly create the TextBoxes in CreateChildControls() or can I? I mean – when is CreateChildControls() called – i know i can call EnsureChildControls() (which i already do in a property to set the innerText of the header – since i need the header to be created before setting its innerText obviously).

How about this

var c = new MyContainerControl();
c.Header = "fun";
c.TextBoxObject = myTextBoxes;

That would raise an error (or at best not create any TextBox'es) if i put the building of the TextBoxes in CreateChildControls().

Would it be more sane to instead just store the Header in a member variable and thus not having to call EnsureChildControls() in the exposed method/property setting the Header innerText. I just don't like this aproach much, since it would be complicating things by adding extra logic to store temporarely and later having to figure out when to set it (probably in PreRender).

Also i guess i could make some kind of Databound control, ensuring the data be present at the time of calling .DataBind(). I really don't like this either since last i looked at creating databound controls it got very complicated.

This really should be an easy task to solve – I know I'm missing something somewhere…

Best Answer

what you're describing IS a databound control. And yes, it's somewhat complicated, but it's the proper design paradigm for this type of instance.

That said, had you considered utilizing the repeater control rather than trying to roll out your own composite which behaves in the exact same manner? Rather than passing it a random object, pass it a collection or an iList with the number of text areas you're wanting.

Related Topic