lonelydev101
lonelydev101

Reputation: 1901

Delete selected items from list box in Powershell

I want to delete selected items from my list, on button click. This is my gui-generated code with logic for delete (please see $Button1.Add_Click method - line 31)

Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()

 $Form = New-Object system.Windows.Forms.Form
 $Form.ClientSize = '400,400'
 $Form.text = "Form"
 $Form.TopMost = $false

 $ListBox1 = New-Object system.Windows.Forms.ListBox
 $ListBox1.text = "listBox"
 $ListBox1.width = 156
 $ListBox1.height = 274
@('Ronaldo', 'Pele', 'Maradona', 'Zidan', 'Pepe') | ForEach-Object {[void] 
$ListBox1.Items.Add($_)}
$ListBox1.location = New-Object System.Drawing.Point(12, 23)
$ListBox1.SelectionMode = "MultiExtended"

$Button1 = New-Object system.Windows.Forms.Button
$Button1.text = "button"
$Button1.width = 60
$Button1.height = 30
$Button1.location = New-Object System.Drawing.Point(197, 16)
$Button1.Font = 'Microsoft Sans Serif,10'

$Form.controls.AddRange(@($ListBox1, $Button1))

$Button1.Add_Click( {
    $items = $ListBox1.SelectedItems
    ForEach ($item in $items) {
        $ListBox1.Items.Remove($item)
    }
})

[void]$Form.ShowDialog()

For some reason it deletes only first item in $items. Others are ignored. Why?

Upvotes: 0

Views: 3628

Answers (1)

Janne Tuukkanen
Janne Tuukkanen

Reputation: 1660

As this error message shows, you can't alter the array in middle of foreach loop:

List that this enumerator is bound to has been modified.
An enumerator can only be used if the list does not change.

You can use while loop and retrieve the SelectedItems again after each removal. The [0] refers to the first element of an array:

while($ListBox1.SelectedItems) {
        $ListBox1.Items.Remove($ListBox1.SelectedItems[0])
}

Upvotes: 2

Related Questions