ASP.NET DropDownList在回发时不保留选定的项目

mat*_*con 16 asp.net postback selection drop-down-menu

我有一个ASP DropDownList,它在Page_Load事件中填充,在我选择一个项目并点击一个按钮后,所选项目被清除并且DropDownList中的第一个项目被选中.(DropDownList仅在页面不回发时填充)

请帮忙

   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;
            }
    }
Run Code Online (Sandbox Code Playgroud)

Nel*_*mel 36

页面生命周期执行以下操作(以及与您的问题无关的其他步骤):

  1. OnInit
  2. 从ViewState填充控件(在回发期间)
  3. 设置选定的值(在回发期间)
  4. Page_Load

您需要启用ViewState,以便在"选择"项目之前填充列表.在这种情况下,请确保不要在Page_Load中重新填充并丢失所选值.做点什么if (!IsPostback) { // Populate }

否则,您必须OnInit在每个页面请求的事件中手动填充列表. Page_Load在生命周期中为时已晚,因此所选项目将丢失.

编辑:

DropDownList还必须有设置的有效值(在浏览器中显示的文本分开).这是通过DataValueField酒店完成的.每个值必须是唯一的,否则只会选择第一个重复项.如果您在浏览器中查看HTML源代码,您应该:

<select>
    <option value="unique_value1">Displayed text1</option>
    <option value="unique_value2">Displayed text2</option>
</select>
Run Code Online (Sandbox Code Playgroud)

唯一值用于在服务器端选择正确的项目.