Retain Selected Value of dynamically bound dropdownlist after postback

user560498 picture user560498 · Apr 30, 2012 · Viewed 14.2k times · Source

I have a dropdownlist which I declare on the aspx markup like so:

<asp:DropDownList ID="State" runat="server"></asp:DropDownList>

Then I bind it on page load like so :

protected void Page_Load(object sender, EventArgs e)
    {
       BindDropdowns();
    }
private void BindDropdowns()
    {
        State.DataSource = DataAccess.GetStates();
        State.DataValueField = "FieldId";
        State.DataTextField = "FieldName";
        State.DataBind();
    }

The selected value is not retained after postback, I also cannot fire the selectedindexchangedevent. What's wrong ?

Answer

MUG4N picture MUG4N · Apr 30, 2012

please change your code like this:

protected void Page_Load(object sender, EventArgs e)
{
   if (!Page.IsPostback)
       BindDropdowns();
}

This means that your dropdown control is only bound once on first pageload