views:

39

answers:

1

Given the following

public class MyControl : CompositeControl
{
    private DropDownList myList;

    protected override void CreateChildControls()
    {
        base.CreateChildControls();

        myList = new DropDownList();
        myList.AutoPostBack = true;
        this.Controls.Add(myList);
        if (!Page.IsPostBack)
        {
            myList.DataSource = MyBLL.SomeCollectionOfItems;
            myList.DataBind();
        }
    }
}

I find that the items in the list persist properly, but when a different control is rendered and then this one is rendered again, the last selected item is not persisted. (The first item in the list is always selected instead)

Should the last selected item be persisted in ViewState automatically, or am I expecting too much?

+1  A: 

I think this is a hidden ViewState issue. You create and bind a control in CreateChildControls. You should only create the control at this place. Move the binding code to the classes load event and use EnsureChildControls.

Dirk
Correct. Thanks for the pointer.
tomfanning