Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

Here is the solution which is best recommended. It lies in understandng the Page Life Cycle correctly!! Postback Controls like Drop Down List restore their posted state (the selected item of a Drop Down List posted). It forgets its selected value because you are rebinding it in Page_Load event, which is after the Drop Down List has been loaded with posted value (because View State is loaded after Page_Init event and before Page_Load event). And in this rebinding in Page_Load event, the Drop Down List forgets its restored selected item. The best solution is to perform the Data Binding in the Page_Init event instead of Page_Load event.

Do something like the below...

Suppose Drop Down List name is lstStates.

protected void Page_Init(object sender, EventArgs e) 
{   
   lstStates.DataSource = QueryDatabase(); //Just an example.  
   lstStates.DataTextField = "StateName";       
   lstStates.DataValueField = "StateCode";    
   lstStates.DataBind(); 
}

ASP.NET loads control's View State after Page_Init event and before Page_Load event, so Drop Down List's selectedIndex will not be affected, and you will get desired results magically!!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top