Reduce Repetitive Code with ASP.NET Custom Controls - Databinding to the Control (Page 3 of 6 )
Databinding is the ideal method for populating a control with data. When you databind a collection or a DataTable to a control, ASP.NET will enumerate through all of the child objects or rows and add them to the control.
The code below overrides the DataBind method of the base class to set up the drop down.
public override void DataBind() { if(_autoLoadData) { Contacts _contacts = new Contacts(); _contacts.LoadFromXmlFile(Page.Server.MapPath("Contacts.xml")); base.DataSource = _contacts; }
The DataTextField and DataValueField properties tell the base class which properties of the Contact class to use when databinding.
In this instance, the Name property will be displayed in the contents of the drop down, while the ID property will serve as the value for each item in the list.
The AutoLoadData property is supplied to allow the developer to specify when the control should handle its own databinding.
You should be aware that if AutoLoadData is false, then you will need to manually supply a data source for the control.
While in most cases it may be useful for the control to databind automatically, if there are multiple instances of the same control on one page then it may be more efficient to do the databinding manually, rather than having each individual instance call the same data source.