我编写了一段代码,将第一个签入列表框中的选定项传输到代码的另一个checkedlistbox.This部分(但是,我仍然必须找到一种方法,以便相同的选定项不会被反复写入).My的第二个目标是从第一个选中的列表框中删除所选的项。我得到的错误是数组超出了界限。
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 { }
}
}发布于 2014-08-13 15:03:20
您的问题是由于在CheckedItems集合上使用indexer造成的。
CheckedItems集合的元素可能比项集合的计数少,因此索引器的值可以不包含在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,因为每个集合都是从索引0开始的。因此,如果您有一个包含10个项的集合,那么有效的索引从0到9。
https://stackoverflow.com/questions/25289605
复制相似问题