views:

279

answers:

4

I have a base class for some kind of user controls, and in that base class and in its inherited classes I want to store some properties. I use

protected override object SaveControlState()
protected override void LoadControlState(object savedState)

methods to save or load my custom values. Since I can work only with 1 parameter of type object, I have to use some kind of list if I want to work with more than 1 variable.

I tried to do it with

[Serializable]
public class ControlSate : Dictionary<string, object>, ISerializable
{   
    void ISerializable.GetObjectData(SerializationInfo info, 
      StreamingContext context)
    {
    }

    public ControlSate(SerializationInfo info, StreamingContext context)
        : base(info, context)
    {    
    }

    public ControlSate()
        : base()
    {
    }
}

but it didn't work, and looking for a solution I have read that Dictionary is not serializable.

So, my question is what type should I use to work with a set of values in user control's state?

+1  A: 

While LoadControlState does pass you an Object it is possible for that Object to be an Object[]. In other words you are more than welcome to store an array of Objects in ControlState. I also believe that ControlState is optimized to work with the System.Web.UI.Pair type so you can create trees of objects in ControlState if you wish.

Please read this excellent article for the best way of storing multiple values in ControlState.

Andrew Hare
thanks, but I don't know how many items will be in the collection, and as far as I know arrays in c# has to be declared with precise length
eKek0
Correct - but you *can* store a List<T> in the Object array and push that into ControlState.
Andrew Hare
A: 

For storing complex state there is the IStateManager interface.

dfowler
A: 

That's odd. If you look at the generic Dictionary<T,U> in Reflector, it has a [Serializable] attribute. I noticed that you have a Dictionary<string,object>, so U = 'object' here. What is the real type of 'U'?. If you are using a complex type for 'U' then that needs to be marked [Serializable] as well. You may also need to explicitly mark each field and /or property as [Serializable] as well. If this doesn't work, it might be worthwhile trying to use a List<KeyValuePair<T,U>>

Abhijeet Patel
A: 

I'd question the srializable attribute on a property as according to the compiler:

Attribute 'Serializable' is not valid on this declaration type. It is only valid on 'class, struct, enum, delegate' declarations.