ASP.NET DropDownList not retaining selected item on postback

mattgcon picture mattgcon · Nov 15, 2010 · Viewed 72.8k times · Source

I have an ASP DropDownList that gets populated on the Page_Load event, after i select an item and hit a button the selected item gets cleared and the first item in the DropDownList gets selected. (The DropDownList is only populated when the page is not postback)

if (!IsPostBack)
{
    List<Country> lCountries = new List<Country>();
    List<CompanySchedule> lCompanySchedules = new List<CompanySchedule>();
    this.Load_Countries(lCountries);
    this.Load_Schedules(lCompanySchedules);
    if (personnelRec == null) 
    { 
        personnelRec = new Personnel(); 
    }
    if (Request.QueryString["UA"] != null && Convert.ToInt32(Request.QueryString["UA"].ToString()) > 0)
    {
        userAccount.ID = Convert.ToInt32(Request.QueryString["UA"].ToString());
        App_Database.Snapshift_Select_Helper.SNAPSHIFT_SELECT_PERSONNEL_APP_ACCOUNT(ref userAccount);
    }

    this.imgEmployeePicture.ImageUrl = "./images/Employees/nophoto.gif";
    if (Request.QueryString["EI"] != null && Convert.ToInt32(Request.QueryString["EI"].ToString()) > 0)
    {
            this.Load_PersonnelRec(Convert.ToInt32(Request.QueryString["EI"].ToString()));
    }
    else
    {
        this.lblChangeDirectionHead.Enabled = false;
        this.lblChangeDirections.Enabled = false;
        this.lbSchedules.Disabled = true;
    }
}

Answer

Nelson Rothermel picture Nelson Rothermel · Nov 15, 2010

The page lifecycle does the following (plus other steps irrelevant to your question):

  1. OnInit
  2. Populate controls from ViewState (during postback)
  3. Set the selected values (during postback)
  4. Page_Load

You need to have ViewState enabled so it can populate the list before it "selects" the item. In this case, make sure you don't repopulate in Page_Load and lose the selected value. Do something like if (!IsPostback) { // Populate }

Otherwise, you have to populate the list manually in the OnInit event on every page request. Page_Load is too late in the lifecycle, so the selected item is lost.

Edit:

The DropDownList must also have valid values set (separate from the text displayed in the browser). This is done through the DataValueField property. Each value must be unique, otherwise only the first duplicate item will ever be selected. If you look at the HTML source in your browser, you should have:

<select>
    <option value="unique_value1">Displayed text1</option>
    <option value="unique_value2">Displayed text2</option>
</select>

The unique values are used for selecting the right item on the server side.