Reputation: 817
I like to know which method should I overload to the object get a custom text string display in PowerShell Windows.Forms.ListBox. I have tried this and other variations but to no avail:
$vms_listbox = New-Object System.Windows.Forms.ListBox
$vms = Get-VM
#
# Overload ToSTring (I thought this would do)
#
$vms | Add-Member ScriptMethod ToString { $This.Name } -Force
$vms | Foreach {
[Void]$vms_listbox.Items.Add($_)
}
I have tried ith Add-Member ScriptProperty, CodeMethod, CodeProperty, but the listbox still not show the value I intend to show which in this case, the Virtual machine name.
I could have add to the list with the virtual name as: Items.Add($_.Name), but I prefer to add the instance to the list so I can retrieve it later.
Thanks in advance.
Upvotes: 2
Views: 3428
Reputation: 54941
You need to tell he listbox which property contains the display-friendly name for the items.
Replace:
$vms_listbox = New-Object System.Windows.Forms.ListBox
with:
$vms_listbox = New-Object System.Windows.Forms.ListBox
$vms_listbox.DisplayMember = "Name"
Upvotes: 3