我有一个问题,当我尝试从代码隐藏中的 asp:listbox 获取 selectedindex 时,它总是保持 -1,即使在页面上它被选中。我每分钟都会完全更新这个列表。为了加载 listItems,整个列表将被删除并再次写回。
代码示例:
<asp:ListBox ID="ListBox1" runat="server"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"
AutoPostBack="false">
</asp:ListBox>
在代码隐藏中:
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
itemsIndex = ListBox1.SelectedIndex.ToString(); //It is always -1
itemToBeRescheduled = ListBox1.SelectedItem.Value;
}
尝试使用 if(!isPostBack).. 但索引保持为 -1,它只从列表中删除了我的项目。
提前致谢!
最佳答案
根据我的经验,当您在回发时再次重新绑定(bind) ListView 时,就会发生这种情况。为了防止这种情况发生,我们通常将绑定(bind)放在!IsPostback内部。
例如,
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListBox1.DataSource = new List<ListItem>()
{
new ListItem("One", "1"),
new ListItem("Two", "2"),
new ListItem("Three", "3")
};
ListBox1.DataBind();
}
}
关于c# - 列表框 SelectedIndex 始终返回 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36632402/