Listbox items duplicating when moved

Ask questions about creating Graphical User Interfaces (GUI) in PowerShell and using WinForms controls.
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
This topic is 4 years and 7 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
jkornhaus
Posts: 3
Last visit: Fri Jan 14, 2022 11:48 am

Listbox items duplicating when moved

Post by jkornhaus »

Hi,

I found this Listbox Capabilities demo on the forums a while back. On Example 2, I was playing with button 1 and button 2 and noticed if I selected say 4-9 and pressed button 1, it would move 4-9 over to listbox4 but make a copy of 5,7,9 on listbox3. If you moved anything from listbox4 to listbox3, it duplicates again.

I thought the code on line 41 & 66 in the Script removed any remnants but this does not seem to be the case. How do you move all the item that you selected and not leave any duplicate / remnants? Buttons 3 and 4 seem to move everything without duplicating.
Attachments
Demo-ListBoxCapabilities.pff
(15.92 KiB) Downloaded 74 times
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Listbox items duplicating when moved

Post by jvierra »

The code for that button is wrong. Here is what it should be:

Code: Select all

$button1_Click={
    $listbox4.Items.AddRange($listbox3.SelectedItems )
    $items = $listbox3.SelectedIndices.Count  - 1
    $items .. 0 | ForEach-Object{$listbox3.Items.RemoveAt($items[$_])}
}
Colelctions must be removed in reverse to avoid having th indexes being reallocated as items are removed.
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Listbox items duplicating when moved

Post by jvierra »

I think this is cleaner and clearer:

Code: Select all

$button1_Click={
    $listbox4.Items.AddRange($listbox3.SelectedItems )
    ($listbox3.SelectedIndices.Count - 1) .. 0 | 
        ForEach-Object{
            $listbox3.Items.RemoveAt($listbox3.SelectedIndices[$_])
        }
}
[code]
This topic is 4 years and 7 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked