Download StateCollection.zip - 925 B
Introduction
While building custom ASP.NET controls I often need to implement IStateManager for collections of objects
in order to persist them in ViewState.
The common way was to create collection by inherit List<T> and implementing IStateManager.
In most of the cases the code was same, I just have to change the generic type of the list.
That's why it was a perfect candidate for generic implementation. Implementation which made
The Generic State Collection gave me the ability to use any kind of state collections without a line
of additional code.
The Code
StateCollection
inherits List<T>
class and implements IStateManager.
Please, note I'm requiring the generic type of StateCollection
to be one that implements
IStateManager by itself.
Here is the source code of StateCollection class:
public class StateCollection<T> : List<T>, IStateManager where T : IStateManager, new(){
#region Fields
bool _tracking;
#endregion
#region Properties
public bool IsTrackingViewState {
get { return _tracking; }
}
#endregion
#region Methods
public void LoadViewState(object savedState) {
object[] state = savedState as object[];
if (state != null) {
T item;
bool exists;
for (int i = 0; i < state.Length; i++) {
item = (exists =( i < this.Count)) ? this[i] : new T();
item.LoadViewState(state[i]);
if (this.IsTrackingViewState)
item.TrackViewState();
if(!exists) Add(item);
}
}
}
public object SaveViewState() {
if (this.Count > 0) {
int count = this.Count;
object[] state = new object[count];
for (int i = 0; i < count; i++) {
state[i] = this[i].SaveViewState();
}
return state;
}
else
return null;
}
public void TrackViewState() {
_tracking = true;
}
#endregion
}
Points of Interest
As example of how to use StateCollection
you can refer to
GoogleMap Control source code.
History
- 22.Mar.2008 - Initial release