DropDown List resets to the first item and doesn't return a selectedvalue

gdubs picture gdubs · Mar 1, 2011 · Viewed 7.4k times · Source

So I have a country dropdownlist and a state dropdownlist which is being populated dynamically based off of the country chosen. When I click the country the state dropdown gets populated just fine but the problem arises when I click a value (state) from the other dropdown, the list instead of retaining the selected item will go back to the first item of the list and no selectedvalue are displayed.

<td><asp:DropDownList ID="ddlState" runat="server"
    DataSourceId="dsStateList"
    DataTextField="state_nm"
    DataValueField="state_cd"
    OnSelectedIndexChanged="ddlState_SelectedIndexChanged"
    AutoPostBack="true"
    AppendDataBoundItems="true" 
    Width="160px" OnDataBound="ddlState_OnDataBound">
    </asp:DropDownList>
</td>

    <asp:DropDownList ID="ddlCountry" runat="server"
    DataSourceId="dsCountryList"
    DataTextField="COUNTRY_NAME"
    DataValueField="COUNTRY_CIA_ID"
    OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged"
    OnDataBound="ddlCountry_OnDataBound"
    AutoPostBack="true"
    AppendDataBoundItems="true" 
    Width="160px">
    </asp:DropDownList>


protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
{
    string comboStateCODE = ddlState.SelectedValue;
    dsCompanyListParam.Text = comboStateCODE;
    ddlCountry.DataBind();
    ddlState.DataBind();
}

protected void ddlState_OnDataBound(object sender, EventArgs e)
{
    ddlState.Items.Insert(0, "Please Select a State");
}
protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)
{
    ddlState.Items.Clear();
    dsStateList.SelectParameters["iCountryID"].DefaultValue = ddlCountry.SelectedValue;

    dsCompanyListParam.Text = ddlCountry.SelectedValue;
    Trace.Warn("ddlCountry_SelectedIndexChanged");

    ddlCountry.DataBind();
    ddlState.DataBind();

}
protected void ddlCountry_OnDataBound(object sender, EventArgs e)
{
    ddlCountry.Items.Insert(0, "Please Select a Country");
}

Answer

Dal picture Dal · Mar 1, 2011

I presume that somewhere in your Page_Load() you are making a call to a method that populates the dropdown... you need to encapsulate this into an IF !PostBack block:

// somewhere in PageLoad()...
If(!IsPostBack)
{
    PopulateDropdown();
}

Using the convention above, the dropdown will only be populated on the first ever page load. What I suspect is happening is that when you make a selection from the other dropdown, the AutoPostBack is executing the Page_Load() method (as it should) and repopulating the dropdowns again.

Using the convention above should help avoid this.