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.
Locked
jkornhaus
Posts: 3
Joined: Sun Jul 07, 2019 3:16 pm

Listbox items duplicating when moved

Post by jkornhaus » Tue Jul 30, 2019 8:27 pm

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 12 times

User avatar
jvierra
Posts: 13803
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: Listbox items duplicating when moved

Post by jvierra » Tue Jul 30, 2019 9:38 pm

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.

User avatar
jvierra
Posts: 13803
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: Listbox items duplicating when moved

Post by jvierra » Tue Jul 30, 2019 9:55 pm

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]

Locked