[英]delete checked items from checkedListBox c#
I want to remove several checked items from checkedListBox but I can't.This is my example.我想从checkedListBox 中删除几个选中的项目,但我不能。这是我的例子。 I was trying it but i was imposiible to get.
我正在尝试,但我不可能得到。
for (int i = 0; i < checkedListBox1.Items.Count; i++){
if (checkedListBox1.GetItemChecked(i))
{
checkedListBox1.Items.Remove(checkedListBox1.CheckedItems[i]);
}
}
Let's say you have a CheckedListBox of 2 items, both checked.假设您有一个包含 2 个项目的 CheckedListBox,均已选中。 If you delete
item 1
then item 2
becomes the new item 1
and hence will never be deleted.如果您删除
item 1
则item 2
将成为新的item 1
,因此永远不会被删除。
This is what's going on in detail:这是正在发生的详细情况:
i
is initialized to 0. i
被初始化为 0。i
is less than checkedListBox1.Items.Count
(which is 2). i
小于checkedListBox1.Items.Count
(即2)。 Loop entered.checkedListBox1.GetItemChecked(i)
returns true. checkedListBox1.GetItemChecked(i)
返回 true。checkedListBox1.Items.Remove(checkedListBox1.CheckedItems[i])
removes item at index 0. checkedListBox1.Items.Remove(checkedListBox1.CheckedItems[i])
删除索引 0 处的项目。i
is incremented to 1. i
增加到 1。i
is not less than checkedListBox1.Items.Count
(which is 1) and the loop exits. i
不小于checkedListBox1.Items.Count
(即1)并且循环退出。 hence item 2
will not be deleted.因此第
item 2
不会被删除。
Reverse the loop and it should work:反转循环,它应该可以工作:
for (int i = checkedListBox1.Items.Count - 1; i >= 0; i--)
{
if (checkedListBox1.GetItemChecked(i))
{
checkedListBox1.Items.Remove(checkedListBox1.Items[i]);
}
}
Another way of doing this is as follows:另一种方法如下:
while (checkedListBox1.CheckedItems.Count > 0)
{
checkedListBox1.Items.RemoveAt(checkedListBox.CheckedIndices[0]);
}
And another:还有一个:
while (checkedListBox1.CheckedItems.Count > 0)
{
checkedListBox1.Items.Remove(checkedListBox1.CheckedItems[0]);
}
Yet another:完后还有:
foreach (var i in checkedListBox1.CheckedIndices)
{
checkedListBox1.Items.RemoveAt(i);
}
Going on:正在进行:
for(var i = 0; i < checkedListBox1.CheckedItems.Count; i++)
{
((IList) checkedListBox1.CheckedItems).Remove(checkedListBox1.CheckedItems[0]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.