我有一个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;
    }
}

最佳答案

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


OnInit
从ViewState填充控件(回发期间)
设置选定的值(回发期间)
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>


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

08-04 17:30