Issue Removing Items from a CheckedListBox

I have checkedListBox (used for removing VMWare Snapshots). I have a function that removes items when clicked, shown below. However, Only half of the checked items gets removed. What am I missing? Every index will get printed out, but only 2 of the 4 checked items gets removed.

$numChecked = $CHECKBOXLIST_Snapshots.CheckedIndices.Count if($numChecked -gt 0){ foreach($i in $CHECKBOXLIST_Snapshots.CheckedIndices) { start-sleep -Milliseconds 500 Write-Host "Number is" $i

$CHECKBOXLIST_Snapshots.Items.RemoveAt($i) }





  • Edited by mxalvis 14 hours 28 minutes ago
September 4th, 2015 12:14pm

Don't use two lists.  Store everything in the listbox and just remove the current item after using it. 

Free Windows Admin Tool Kit Click here and download it now
September 4th, 2015 12:40pm

This is not helpful as the logic to remove from checklistbox has no dependency on the array of snapshots. Review my initial post again, as I simplified and updated it.
September 4th, 2015 12:47pm

This is not helpful as the logic to remove from checklistbox has no dependency on the array of snapshots. Review my initial post again, as I simplified and updated it.

That is how listboxes are designed to work. We store the objects in the listbox.  When we access the "checkeditems" or "selecteditems" list we get the object ad can use it as an object.  There is really no need for two arrays (a listbox is an array - a visual array of objects).

Don't use indices.  Use the CheckedItems array as it is the item and not a number.

Too load a listbox use "DataSource"  and "DisplayMember" to load the objects.  Cast the object collection to an [arraylist] and it will lload easily.

This is how we programmers have been doing this for two decades.  GO and reead the tutorials on WIndows Forms Listbox/CheckedListBox. 

Example:

$checkedlistbox1.CheckedItems | %{ Remove-VM $_; $checkedlistbox1.Items.Remove($_)}

That is pseudo as it need error checking and logging. We can also start a new list with  the removed items for visual feedback.

In a while I will find a good example in my script bin.

Free Windows Admin Tool Kit Click here and download it now
September 4th, 2015 12:58pm

As oppose to "RTFM" recommendation, can you explain why my logic presented does not clear every item as it (appears) it should? 
September 4th, 2015 1:01pm

It is the old chicken trying to eat its tail that is your issue.  Every time you remove an item by number the whole list is renumbered.  Don't use numbers use items.  They don't change.
Free Windows Admin Tool Kit Click here and download it now
September 4th, 2015 1:05pm

That is helpful. thanks
September 4th, 2015 1:08pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics