Listbox Move Up Down Buttons.ps1 shows the event handlers for moving a selected item up and down in a PowerShell listbox. I wrote it because couldn’t find it anywhere else.
$handler_DownButton_Click= { #only if the last item isn't the current one if(($ListBox1.SelectedIndex -ne -1) -and ($ListBox1.SelectedIndex -lt $ListBox1.Items.Count - 1) ) { $listbox1.BeginUpdate() #Get starting position $pos = $Listbox1.selectedIndex # add a duplicate of item below in the listbox $ListBox1.items.insert($pos,$listbox1.Items.Item($pos +1)) # delete the old occurrence of this item $ListBox1.Items.RemoveAt($pos +2 ) # move to current item $ListBox1.SelectedIndex = ($pos +1) $ListBox1.EndUpdate() }ELSE{ #Bottom of list, beep [console]::beep(500,100) } } $handler_UpButton_Click= { # only if the first item isn't the current one if($ListBox1.SelectedIndex -gt 0) { $listbox1.BeginUpdate() #Get starting position $pos = $Listbox1.selectedIndex # add a duplicate of original item up in the listbox $ListBox1.items.insert($pos -1,$listbox1.Items.Item($pos)) # make it the current item $ListBox1.SelectedIndex = ($pos -1) # delete the old occurrence of this item $ListBox1.Items.RemoveAt($pos +1) $ListBox1.EndUpdate() }ELSE{ #Top of list, beep [console]::beep(500,100) } }
Some things to note. I have error handling for moving too far up or down. The error is a beep using the [console] accelerator. BeginUpdate turns off the display while making changes to the listbox. EndUpdate turns them back on.