views:

46

answers:

1

Maybe it's been a long day but I'm having trouble persisting a collection backed by the ASP.NET ViewState in a CompositeControl. Here's a simplified version:

public class MyControl : CompositeControl
{
  public Collection<MyObject> MyObjectCollection
  {
    get { 
      return (Collection<MyObject>)ViewState["coll"] == null ? 
        new Collection<MyObject>()
        : (Collection<MyObject>)ViewState["coll"];
    }
    set { ViewState["coll"] = value; }
  }
}


public partial class TestPage : System.Web.UI.Page
{
  protected void btn_Click(object sender, EventArgs e)
  {
      myControl1.MyObjectCollection.Add(new MyObject());
  }
}

When the button is clicked, the event hander btn_Click executes fine, but the setter for MyObjectCollection never gets called, hence the new MyObject() never gets persisted.

I think I'm just having a blonde moment. Anyone fancy helping out?

+1  A: 

Calling Add() on your collection isn't the same as calling the setter on the MyObjectCollection property.

It's for this reason that tools like FxCop suggest that you don't have setters on Collection properties - either make the setter private or remove it completely.

You may need to implement your own collection type and override the Add and Remove methods, such that when they are called, the persistence code is executed.

womp
In retrospect, obvious solution. Thanks for the pointer... really was a long day.
tomfanning