How to restrict a custom databound control to accept my custom collection as datasource?
I have created a custom databound control as per my requirements and now I want to restrict this control should take custom collection as datasource instead of every collection which is impe开发者_如何转开发lmented IEnuberable interface.
Is it possible to restrict? If yes, how to restrict this?
Thanks in advance..
Can you put a guard in the setter of DataSource ?
public object DataSource
{
get
{
return ....;
}
set
{
if (value is typeof(myCollection) )
this.dataSource = value;
else
throw InvalidOperationException("DataSource must by {0}" typeof(myCollection).FullName;
}
}
One of the simplest way is to put the type check in Data Source related properties. For example, @Preet has already pointed out overriding DataSource
setter. Only issue with the approach, that you need to also take care of a situation where the control is bound using DataSourceID
.
I will rather recommend putting a type check in DataBoundControl.PerformDataBinding method - this is of course assuming that you have inherited from DataBoundControl
class. This method gets called so that derived class can actually bound the data - so it stands as a good candidate. Another equivalent is to put check in OnDataBind
.
Yet another way is to expose specific collection as a property to accept the data. In such case, you should avoid exposing DataSource
related properties.
精彩评论