【问题标题】:Listbox SelectedIndex always returns -1列表框 SelectedIndex 始终返回 -1
【发布时间】:2016-04-14 19:36:55
【问题描述】:

我有一个问题,当我尝试从代码隐藏中的 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 并且它只从列表中删除了我的项目。

提前致谢!

【问题讨论】:

  • AutoPostBack="false"?
  • 不管是真还是假,选择的索引都是-1,但如果设置为真,则不允许选择列表中的项目。
  • 您应该启用 AutoPostBack 并在删除所有项目之前获取选定的索引。您必须检查每分钟更新列表的方式是否导致所选索引丢失。

标签: c# asp.net


【解决方案1】:

根据我的经验,当您再次在回发时重新绑定 ListView 时会发生这种情况。为了防止它,我们通常将绑定放在 !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();
    }
}

【讨论】:

  • 这个回发效果很好,但只有一次页面加载,我如何用动态出现和消失的 listItems 更新列表?
【解决方案2】:

当我有:

<asp:ListBox ID="ListBox1" runat="server" Height="140px" Width="290px" Font-Size="22px" autopostback="true" OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
<asp:ListItem>Item 1</asp:ListItem>
<asp:ListItem>Item 2</asp:ListItem>
<asp:ListItem>Item 3</asp:ListItem>
<asp:ListItem>Item 4</asp:ListItem>
<asp:ListItem>Item 5</asp:ListItem>
<asp:ListItem>Item 6</asp:ListItem>
</asp:ListBox>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

还有:

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (ListBox1.SelectedIndex == -1)
        TextBox1.Text = "-1";
    else
        TextBox1.Text = ListBox1.SelectedItem.Text;
}

我没有得到 ListBox1.SelectedIndex = -1。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    • 1970-01-01
    • 2017-08-10
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    相关资源
    最近更新 更多