【问题标题】:Visual Studio 2012 C#: Remove ALL *Checked Items in a CheckedListBoxVisual Studio 2012 C#:删除 CheckedListBox 中的所有 *Checked 项
【发布时间】:2014-02-11 09:56:00
【问题描述】:

我是 C# 以及更重要的是 Visual Studio 2012 的极端新手,如果这似乎是一个简单的问题,我深表歉意。所以我正在制作一个待办事项列表应用程序作为我使用 VS2012 的第一个小项目。我有一个名为“checkedListBox1”的 CheckedListBox 和一个用于一次性删除标记(或选中)项目的按钮,名为“markButton”。我编写了以下代码,但正如您在我的评论中看到的那样,它做了一些奇怪的事情:从我拥有的已检查项目集合中删除所有其他已检查项目。


private void markButton_Click(object sender, EventArgs e)
{
    // create a collection of the checked items in the to do list
    // then remove each of them.
    // **** ERROR: It deletes every other checked item 
    // so it deletes indeces 0..2..4..6... each time.
    CheckedListBox.CheckedItemCollection checkedItems = checkedListBox1.CheckedItems;
    for (int i = 0; i < checkedItems.Count; i++)
    {
        checkedListBox1.Items.Remove(checkedItems[i].ToString());
    }
}

【问题讨论】:

  • 那么你想删除所有选中的项是什么?

标签: c# visual-studio-2012 checkedlistbox items removeall


【解决方案1】:

当您删除一个项目时,checkedItems 集合会变小。只需重复删除第一个:

while (checkedItems.Count > 0)
{
    checkedListBox1.Items.Remove(checkedItems[0]);
}

或者以相反的顺序移除:

for (int i = checkedItems.Count; i > 0; )
{
    checkedListBox1.Items.Remove(checkedItems[--i]);
}

更好的是,使用 CheckedIndices,这样可以避免在重复的情况下搜索匹配项和混淆:

var checkedItemIndices = checkedListBox1.CheckedIndices;
for (int i = checkedItemIndices.Count; i > 0; )
{
    checkedListBox1.Items.RemoveAt(checkedItemIndices[--i]);
}

【讨论】:

  • 谢谢,我几分钟前就想通了,正准备回答,但我没有足够的代表。是的,这就是我使用的解决方案,只是我没有考虑 > 0 部分,这使它更简单。我创建了一个变量来存储原始 Count,然后将其用作我的 'i
  • 感谢格兰特。我用不同的方式修复了它,但你的观点是有效的。
猜你喜欢
  • 2014-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-09
相关资源
最近更新 更多