Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Visual Studio 2012 C#:删除CheckedListBox中的所有*选中项_C#_Visual Studio 2012_Checkedlistbox_Items_Removeall - Fatal编程技术网

Visual Studio 2012 C#:删除CheckedListBox中的所有*选中项

Visual Studio 2012 C#:删除CheckedListBox中的所有*选中项,c#,visual-studio-2012,checkedlistbox,items,removeall,C#,Visual Studio 2012,Checkedlistbox,Items,Removeall,对于C#和更重要的Visual Studio 2012来说,我都是一个极端的新手,如果这似乎是一个简单的问题,那么很抱歉。因此,我正在制作一个待办事项列表应用程序,作为我使用VS2012的第一个小项目。我有一个名为“checkedListBox1”的CheckedListBox和一个名为“markButton”的按钮,用于同时删除标记(或选中)的项目。我已经编写了以下代码,但正如您在我的评论中看到的,它做了一些奇怪的事情:从我的已检查项集合中删除所有其他已检查项 private void ma

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


private void markButton\u单击(对象发送者,事件参数e)
{
//创建待办事项列表中选中项目的集合
//然后将它们分别移除。
//****错误:它会删除所有其他选中项
//所以每次它都会删除索引0..2..4..6。
CheckedListBox.CheckedItemCollection checkedItems=checkedListBox1.checkedItems;
for(int i=0;i
删除项目时,
checkedItems
集合会变小。只需重复移除第一个:

while (checkedItems.Count > 0)
{
    checkedListBox1.Items.Remove(checkedItems[0]);
}
或按相反顺序移除:

for (int i = checkedItems.Count; i > 0; )
{
    checkedListBox1.Items.Remove(checkedItems[--i]);
}
更好的方法是使用checkedDices,这样可以避免在重复项的情况下搜索匹配项和混淆:

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

那么,您想删除所有选中的项目吗?谢谢,我几分钟前就想好了,正要回答,但我没有足够的代表。是的,这是我使用的解决方案,只是我没有考虑到>0部分,这使它更简单。我创建了一个变量来存储原始计数,然后将其用作我的“I<\u\u”部分。所以你的方法比较干净,谢谢!谢谢格兰特。我用另一种方法修正了,但你的观点是正确的。
var checkedItemIndices = checkedListBox1.CheckedIndices;
for (int i = checkedItemIndices.Count; i > 0; )
{
    checkedListBox1.Items.RemoveAt(checkedItemIndices[--i]);
}