Losing DropDownList items on post back

649 views Asked by At

I have an webforms ASPX page, which has a dynamically added user control. The user control has two DropDownLists, one is in an UpdatePanel as its items depend on the selection in the first DropDownList.

The problem is that if you do not change the value of the first DropDownList the value of the second DropDownList does not get saved. If you do change the value of the first DropDownList then it works fine.

This is how it works briefly...

The first time the page loads, the previous values are set. This happens in the main ASPX page Page_Load event where the user control is dynamically added and the initial values are set through a property of the user control. The property sets the selected value of the first DropDownList, triggers the SelectedIndexChanged event which populates items in the second DropDownList with choices based on the first DropDownList selection, and then selects the previous value of the second DropDownList.

Then in the main ASPX page, the user control is dynamically added again on post back in the PreLoad event.

Viewstate is fully enabled throughout.

I have debugged and on post back the second DropDownList has no Items. Even during the UpdatePanel partial post back the items collection is empty. However, if the first DropDownList is changed then the Items collection is correct - it's only if the second DropDownList is last populated on the initial load that the problem happens.

Here's the relevant parts of the code...

Any help greatly appreciated.

ASPX page:

protected void Page_PreLoad(object sender, EventArgs e)
{
    if (Page.IsPostBack)
    {
        PopulateTemplateOptions();
    }
}

protected void PopulateTemplateOptions(bool init = false)
{
     //this is where the control is dynamically added
     //If not post back then initial values are set by passing values to 
     //user control's TemplateOptions property
}

User control:

public string TemplateOptions
{
    set
    {
         //this is where the initial values are set
    }
}

protected void ddlEnquirySubjectDefault_SelectedIndexChanged(object sender, EventArgs e)
{
    //this is where items are added to the second drop down list based on the selection in the first one.
}

(These are the only parts that are relevant, but there's another 7,000 lines of code I didn't include.)

1

There are 1 answers

0
Pecheneg On

Here are two of my ideas:

1) This line might be wrong in your code: if (Page.IsPostBack)

It must be if (!Page.IsPostBack), although I never used Page_PreLoad event so I am not sure if it is right.

2) Try to do what you want in Page_Init event instead. I use it on my projects, without problem.