Prior to ASP.Net 2.0, you had to write a custom collection which explicitly implemented IList interface and then you had to expose custom typed methods and properties (IList can deals with objects). You also had to implement IStateManager interface in this custom collection class so the items can be stored in view state.
Fortunately, ASP.Net 2.0 has a class collection class which serves this specific purpose i.e. creating a custom collection which can be stored in the view state. All you have to do is inherit from StateManagedCollection and add your custom typed properties e.g. Add(), Remove(), IndexOf() etc. The StateManagedCollection will automatically manage the items in the collection in ViewState. Please note that StateManagedCollection expects items stored inside it implement IStateManager interface.
Suppose, you need to have two collection properties viz. Holidays (which holds Holiday objects) and Leaves (which holds Leave objects). The code in both the collection classes will more or less same except for the custom typed properties e.g. Holidays.Add() would expect an object of Holiday class and Leaves.Add() will expect an object of a Leave class. The definitions of the functions would be as follows:
Holidays.Add(Holiday h) { // code to add holiday to collection }
Leaves.Add(Leave l) { // code to add leave to collection }
To tackle this problem I created a generic StateManagedCollection (called StateManagedCollection
For this, I first created an abstract class called StateManagedEntity which all the item classes (e.g. Holiday, Leave etc have to derive from). StateManagedEntity class creates a private StateBag and exposes a protected property called ViewState in which the derived classes can store their data etc. StateManagedEntity also takes care of implementing IStateManager interface.
The StateManagedCollection
Once the item class (Holiday, Leave etc) have inherited from StateManagedEntity, all it takes is to declare a property in the custom control like:
public StateManagedCollection
{
get { }
set { }
}
You don’t even have to declare a collection class inheriting from StateManagedCollection. Check out the sample and code. Issues and feedback is welcome.
The code can be download here.