I have the following property in a custom control:
List<myClass> _items;
public List<myClass> Items{
get { return _items; }
set { _items= value; }
}
In my codebehind, I add items to the collection as in...
myCustomControl.items.Add(new myClass());
However, these are not persisted across postbacks. What is the proper way to allow persistance in custom controls?
Yikes! Don't put a List<> into the ViewState! It'll be massive!
If you add a List<string> that contains two elements - "abc" and "xyz" into the ViewState, it'll grow by 312 bytes.
If instead you add a string[] that contains the same two elements, it'll only grow by 24 bytes.
And that's just lists of strings! You can put your classes in there as Corey Downie suggests, but your ViewState will mushroom!
To keep it a sensible size, you'll have to go to some effort to convert your list of items into arrays of strings and back again.
As an alternative, consider putting your objects into the Session: that way your objects will be stored on the server, instead of being serialized into the ViewState and sent to the browser and back.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With