user560498
user560498

Reputation: 547

Retain Selected Value of dynamically bound dropdownlist after postback

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 ?

Upvotes: 1

Views: 14434

Answers (2)

MUG4N
MUG4N

Reputation: 19717

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

Upvotes: 5

Arion
Arion

Reputation: 31239

You have to use the AutoPostBack="true".

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

And also state that the witch event handler like this:

<asp:DropDownList ID="State" AutoPostBack="true" 
OnSelectedIndexChanged="State_SelectedIndexChanged" 
runat="server"></asp:DropDownList>

Then in code. Bind just when not post back:

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

protected void State_SelectedIndexChanged(object sender, System.EventArgs e)  
{  
    var somevalue= State.SelectedValue;  
} 

Upvotes: 2

Related Questions