Question

Is there a way to disable a few items in the System.Windows.Forms.ListBox in PowerShell?

i.e. ListBox contains:

item-a
item-b
item-c
item-d
item-e

and I like to make for example, item-c and item-e not selectable. Thanks!

Was it helpful?

Solution

Short answer: There is no native Disable/Enable items in the ListBox control.

I see two ways to do it:

  1. Have an array of items that you don't want selectable. When handling your click event, check to see if the item is one that you don't want selected, and do nothing.
  2. The easier method: Create a custom control. See: How to Disable Selected Item in List Box

OTHER TIPS

# Events
$listBox.add_selectedindexchanged({
    foreach ($item in $listbox.SelectedItems) {
        if (***condition for being unselectable***) {
            $listbox.SelectedItems.Remove($item)
            break
        }
    }
}

Every time the user selects an item, this event checks the select items list for "unselectable" items (which you specify with the condition). if found, they are removed from the list. The "break" is included to avoid the non-terminating error when the foreach loop runs on a list that has been changed. This solution may not work for Shift-click multi-selection if multiple unselectable items are selected at once, but could be modified (probably).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top