Creating DataBound Control
The other day at work, I was working with working with collection of data from database and wondered how hard would it be to implement a custom DataBound control. Surely enough on researching, I found out that you can inherit from CompositeDataBoundControl and override CreateChildControls to bind the data to the markup user has specified in ItemTemplate property of the control. Here is an example of a SimpleDataBoundControl class that I have created that inherits from CompositeDataBoundControl.
In the above code, SimpleDataBoundControl supports ItemTemplate property where the user can specify their markup and use the databinding syntax to read from their datasource. I am also overriding the CreateChildControls method but this method is not the same method defined by the webcontrol class. In fact CreateChildControls take enumerable collection to which we are binding. Second parameter, databinding, indicates wether we are binding to the datasource or not. Databinding parameter would usually have a value of true when you are binding for the first time. On subsequent postback the data would be supplied to the DataBound control from viewstate. So on postback databinding would be false when the control is restored from viewstate. CreateChildControls method is the place where you would want to put your binding logic because it gets called by the framework whenever the control needs to get bound. Therefore in my CreateChildControls, I am simply enumerating through my collection and instantiating my template inside of a simpleDataItem container. Here is a how my SimpleDataItem class looks like.
SimpleDataItem class simply acts as a container where ItemTemplate gets instantiated in. SimpleDataItem class inherits from IDataItemContainer so that user can use Eval or databinding syntax to read the properties from their source.
In the end part of CreateChildControls, I am explicitly calling DataBind method. This is required for the databinding expressions used in ItemTemplate to be evaluated.
By default my SimpleDataBoundControl renders as span tag. In order to render my control as a div, I am also overriding the TagKey and setting it to a div tag.
In order to use our SimpleCompositeDataBoundControl, you have simply register the server control specify the datasource and declare how your markup would look like in itemtemplate. Here is an illustration.