gpt4 book ai didi

c# - 列表框 SelectedIndex 始终返回 -1

转载 作者:行者123 更新时间:2023-11-30 23:27:09 25 4
gpt4 key购买 nike

我有一个问题,当我尝试在代码隐藏中从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com