CompositeDataBoundControl explained

The .Net framework version 2.0 includes some new base classes that make creating custom ASP.Net controls much easier. Among them is the CompositeDataBoundControl class intended to aid in the development of custom databound controls that are made up of other Controls.

Under most circumstances, all the control author has to do is override the CreateChildControls method. The exact method signature is:

protected abstract int CreateChildControls (
 IEnumerable dataSource,
 bool dataBinding
)

Note the int return value -- this should be the number of data items in the data source that your control acted on when processing the data source. This should become clear in a minute.

The CreateChildControls method will be called under two distinct scenarios: when your control is databound (and a dataSource is supplied) and on postback (when a data source is NOT available). Under this second scenario, the dataSource value will be an array of null's of the length you returned when the control was first databound. It is up to you to recreate enough of the control structure in the second scenario for the event code to work.

Here's a rough example. Say you have a custom control that renders a Label and a Button for each data item. The dataSource contained 5 items and so your control rendered 5 Label+Button combinations and the CreateChildControls method returned 5. In order for the button click event to work on postback, the Buttons have to be recreated on postback, but if all that is needed are Buttons, it would be inefficient to re-bind or even to employ ViewState. What happens is that on PostBack the CreateChildControls is called with an array of 5 nulls and dataBinding set to false. All you have to do in your code is detect that condition and recreate the 5 buttons. Voila, events work!

Hope that helps someone.

posted @ Tuesday, February 14, 2006 2:39 PM

Print

Comments on this entry:

# re: CompositeDataBoundControl explained

Left by Mehdi at 4/13/2006 5:30 AM
Gravatar
Hi and thanks for this blog

I wanted to create a control composed of an Image and a DropDownList and I succeded to do that by extedning DataBoundControl Class and rendreing the child controls in render method, I tried many times to use CompositeDataboundControl but I failed because there is no documentation about that,

If we can do the same thing with DataBoundControl what are the apports of CompositeDataBoundControl ??

Best Regards
Fekih Mehdi
Sun Certified Programmer For The Java 2 Platform 1.4
Comments have been closed on this topic.