The DataSource Property
In ASP.NET 1.x, a data-bound control is centered around the
DataSource property. The property points to the object that feeds the control with data. The final user interface of the control reflects the contents of the data source object. So when you get to write a new custom data-bound control, adding the
DataSource property is the first step. The following code shows the typical implementation, borrowed from one of the many ASP.NET native data-bound controls.
private object _dataSource;
public object DataSource
{
get {return _dataSource;}
set
{
if (value == null ||
value is IListSource ||
value is IEnumerable)
_dataSource = value;
else
throw new ArgumentException();
}
}
As the preceding code demonstrates, the data source is not persisted anywhere, let alone in the page's ViewState. Furthermore, the set accessor of the property performs a type checking to ensure that invalid objects are not bound. Null is usually considered a valid value for the
DataSource property, and so it is for any object that implements either the IEnumerable or the
IListSource interface. It goes without saying that the code snippet above is only a sample. You can modify the implementation at will to make the set accessor throw a different exception, accept a particular type, or refuse null values.
IEnumerable is the base interface for .NET data binding. It exposes an enumerator object to support a simple iteration over a collection. Any managed object that implements, directly or indirectly, IEnumerable can be associated to a data-bound control.
You typically use IListSource to return a list that can be used as a data source from an object that does not implement IEnumerable itself. The interface is supported by most built-in data-bound controls and implemented by a couple of key data objectsDataSet and DataTable. In other words, if you can bind a DataTable to a DataGrid or a DropDownList, it's because of the IListSource interface.
private class DataTable : MarshalByValueComponent,
IListSource, ISupportInitialize, ISerializable
If you ever wrote a custom ASP.NET control, you know that most of the public properties are persisted in the ViewState. As mentioned earlier, this doesn't happen to be the case with
DataSource. The reason is that the data source is potentially too large of an object to be effectively stored in the ViewState. Storing the data source in the ViewState is not an optiondoing that would have serious repercussions on the performance of the page.
So what's up with non-persistent properties when the page that hosts the control posts back? Those properties are blank upon postback and must be reinitialized to work properly across two successive requests.