繁体   English   中英

从选中的列表框中删除选定的项目

[英]removing selected items from a checked list box

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

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 { }
        }
}

您的问题是由于在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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM