Persisting a collection backed by viewstate in a CompositeControl

Posted by tomfanning on Stack Overflow See other posts from Stack Overflow or by tomfanning
Published on 2010-04-28T16:46:50Z Indexed on 2010/04/28 17:03 UTC
Read the original article Hit count: 320

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?

© Stack Overflow or respective owner

Related posts about viewstate

Related posts about composite-controls