【问题标题】:removing selected items from a checked list box从选中的列表框中删除选定的项目
【发布时间】:2014-08-13 15:00:50
【问题描述】:

我编写了一个代码,将第一个选中列表框中的选定项目转移到另一个选中列表框中。这部分代码有效(但是我仍然必须找到一种方法,这样相同的选定项目就不会被一遍又一遍地写入)。我的第二个目标是从第一个选中列表框中删除选定的项目。我得到的错误是数组超出范围。

private void button_ekle_Click(object sender, EventArgs e)
{   
        int i = 0;
        int k = 0;
        i = clb_input.Items.Count; 
        //the number of items in the first checkedlistbox
        for (k = 0; k <i; k++)
        {
            if (clb_input.GetItemChecked(k) == true)
            {   
               //clb_output is the second checkedlistbox

                clb_output.Items.Add(clb_input.Items[k]);
                clb_input.Items.Remove(clb_input.CheckedItems[k]);
                i--;
            }
            else { }
        }
}

【问题讨论】:

    标签: c# winforms checkedlistbox


    【解决方案1】:

    您的问题是由在 CheckedItems 集合上使用索引器 k 引起的。
    CheckedItems 集合的元素可能少于 Items 集合的计数,因此索引器可能具有 CheckedItems 集合中未包含的值。

    但是,当您需要这种代码时,通常会反转循环。
    从终点出发,走向起点

    private void button_ekle_Click(object sender, EventArgs e)
    {   
        for (int k = clb_input.Items.Count - 1; k >= 0; k--)
        {
            if (clb_input.GetItemChecked(k) == true)
            {   
                clb_output.Items.Add(clb_input.Items[k]);
    
                // Remove from the Items collection, not from the CheckedItems collection
                clb_input.Items.RemoveAt(k);
            }
            else { }
        }
    }
    

    您还应该记住,当您希望使用传统的 for 循环遍历集合时,您的限制索引值是项目数减 1,因为 NET 中的每个集合都从索引 0 开始。所以,如果您有一个集合有 10 个项目的有效索引是从 0 到 9。

    【讨论】:

    • 我已经按照你的建议重写了代码,但我仍然遇到同样的错误:\
    • @melek_3 将删除行更改为 clb_input.Items.RemoveAt(k);
    • @LarsTech 我没有注意到这一点。你是绝对正确的。 k 不是 CheckedItems 集合中的有效索引。我会更新答案谢谢
    • @LarsTech 是的,最后提到,0-9 的 10 个项目集合。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多