aspx ListBoxis not working (SelectedIndex)

本文关键字:SelectedIndex working ListBoxis not aspx | 更新日期: 2023-09-27 18:03:10

我在我的aspx页面:

<asp:ListBox ID="ListBoxDelete" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ListBoxDelete_SelectedIndexChanged1"></asp:ListBox>

背后的代码:

protected void Page_Load(object sender, EventArgs e){
   ListBoxDelete.Items.Clear();
   List<string> itens = new List<string>();
   for(var item in itens){
      ListBoxDelete.Items.Add(item);
   }
}
protected void ListBoxDelete_SelectedIndexChanged1(object sender, EventArgs e){
   int x = ListBoxDelete.SelectedIndex;
   doSomething(x);
}

My selecteindex is not working…如果我没记错的话,这个值总是-1。有什么问题吗?

aspx ListBoxis not working (SelectedIndex)

按如下方式更改代码并尝试

protected void Page_Load(object sender, EventArgs e){
if(!IsPostBack)
{
   ListBoxDelete.Items.Clear();
   List<string> itens = new List<string>();
   for(var item in itens){
      ListBoxDelete.Items.Add(item);
   }
}
}

使用IsPostBack更新Page_Load

protected void Page_Load(object sender, EventArgs e){
 if (!IsPostBack)
    {
     ListBoxDelete.Items.Clear();
     List<string> itens = new List<string>();
      for(var item in itens){
       ListBoxDelete.Items.Add(item);
     }
  }
}