【问题标题】:Using Loop To Select/Remove Options From Listbox使用循环从列表框中选择/删除选项
【发布时间】:2014-03-17 19:32:28
【问题描述】:

所以基本上我使用 FOR 循环从列表框中添加和删除选项。 It functions correctly when selected 1 option (from either remove or select) and it functions correctly when I select two separate options (For example, item[0] and item[4]).

但是,当我尝试选择所有选项或选择并排的两个项目([2]、[3].. 等)时,我遇到了麻烦

这是我的 select 函数循环:

protected void btnSelect_Click(object sender, EventArgs e)
{
    for (int intCounter = 0; intCounter < lbSnacks.Items.Count; intCounter++)
    {
        if (lbSnacks.Items[intCounter].Selected) // if the snack is selected
        { // add the listitem to the lbSelected listbox
            lbSelected.Items.Add(lbSnacks.Items[intCounter]);
        }

    }
    for (int intCounter = 0; intCounter < lbSnacks.Items.Count; intCounter++)
    {
        if (lbSnacks.Items[intCounter].Selected) // if the snack is selected
        { // add the listitem to the lbSelected listbox
            lbSnacks.Items.Remove(lbSnacks.Items[intCounter]);
        }

    }
}

该错误基本上是将项目放入“已选择”列表框中,但在原始“小吃”框中留下了两个选项之一。

有什么想法吗?

【问题讨论】:

    标签: c# asp.net for-loop listbox visual-web-developer-2010


    【解决方案1】:

    问题是,当您删除一个项目时,所有其他项目都会向下移动 - 这意味着下一次循环迭代(因为它会增加您的索引)“跳过”一个项目。

    有多种方法可以处理这个问题。最简单的就是向后循环:

    for (int intCounter = lbSnacks.Items.Count-1; intCounter >= 0; intCounter--)
    {
        if (lbSnacks.Items[intCounter].Selected) // if the snack is selected
        { // add the listitem to the lbSelected listbox
            lbSelected.Items.Add(lbSnacks.Items[intCounter]);
            lbSnacks.Items.Remove(lbSnacks.Items[intCounter]);
        }
    }
    

    这样,当项目“移动”时,这并不重要,因为你已经处理了这些项目。

    【讨论】:

    • 非常感谢里德!我正在努力学习循环,但我一直在练习并开始掌握它。
    猜你喜欢
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 2019-04-18
    • 1970-01-01
    • 2013-07-13
    • 1970-01-01
    • 2010-09-27
    相关资源
    最近更新 更多