ASP.Net下拉列表没有返回selectedindexchanged事件的索引

时间:2011-06-27 15:17:35

标签: c# .net asp.net drop-down-menu

我有一个dropdownlist控件,其中有一个正确触发的selectedindexchanged 事件。但是,从列表中选择项目时,返回到selectedindexchanged事件的索引值不会更改;列表框弹出列表中的第一个项目。任何帮助,将不胜感激。 〜苏珊〜

ASP DROP DOWN LIST CONTROL

 <asp:DropDownList ID="CuisineList" runat="server" Width="100" 
    AutoPostBack = "true" onselectedindexchanged="CuisineList_SelectedIndexChanged" >
 </asp:DropDownList>

在PAGELOAD活动中控制数据:

 protected void Page_Load(object sender, EventArgs e)
 {
    //Load drop down lists for restaurant selection

    BLgetMasterData obj = new BLgetMasterData();

    var cusineList = obj.getCuisines();
    CuisineList.DataSource = cusineList;
    CuisineList.DataBind();
    CuisineList.Items.Insert(0, "Any");

SELECTEDINDEXCHANGEDEVENT:

   protected void CuisineList_SelectedIndexChanged(object sender, EventArgs e)
    {

        if (IsPostBack)
        {
            string def = this.CuisineList.SelectedItem.Value;
            //aLWAYS returns index '0'
        }
    }

1 个答案:

答案 0 :(得分:14)

您需要在page_load事件中将Dropdownlist绑定代码放在!IsPostBack()下。像...

protected void Page_Load(object sender, EventArgs e) { 
 if(!IsPostBack)
 {
  BLgetMasterData obj = new BLgetMasterData();

  var cusineList = obj.getCuisines();
  CuisineList.DataSource = cusineList;
  CuisineList.DataBind();
  CuisineList.Items.Insert(0, "Any");
 }
}

原因:每当您的SelectedIndex更改事件触发时,Page_load事件都会在SelectedIndex更改事件和您的下拉数据rebinded之前调用这就是你currect selection was lost

的原因