Trying to store a collection of information in a microsoft combobox dropdown item, so that when it's selected, you can pull those values out (similar to react etc.) Is this possible?
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$combo = New-Object system.Windows.Forms.ComboBox
$combo.Items.add("test")
#get value of selected item here (this code does not work)
write-output($combo.Items[$combo.SelectedIndex].value)
In this example:
$DBArray = Get-Content "$Global:DashboardDir\IncludeFiles\Datapools\Tables\Tables.txt"
#Setup Table Dropdown
foreach ($Database in $DBArray) {
$info = $database.split("|")
if ($Database -ne 'SQLServer|DBName|TableName') {
$SelectQueryCDC_Tables.Items.add(@{
value = $info
display = "CDC Enabled for $($info[2])?"
})
}
}
I would like to store the full $info array as a value somewhere so that I can manipulate it later, whilst still only displaying the display
property.
CodePudding user response:
You just need to remove the .value
property accessor:
PS C:\WINDOWS\system32> $combo.Items[$combo.SelectedIndex]
test
This is because the Items
property is a collection of objects, and there is no value
property on an object:
PS C:\WINDOWS\system32> $combo.Items.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
False False ObjectCollection System.Object
PS C:\WINDOWS\system32> $combo.Items[$combo.SelectedIndex].GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
Now that you've updated your question to indicate that you're adding hastables to the collection, you can use the key of the item in the hashtable that you want to display:
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.Application]::EnableVisualStyles()
$combo = New-Object system.Windows.Forms.ComboBox
$combo.Items.add(@{
value = "the info array would be here"
display = "CDC Enabled display message here"
})
#show the display message of the selected item here
write-output($combo.Items[$combo.SelectedIndex]['display'])
You can read more about how to use hashtables here: Everything you wanted to know about hashtables
Ok, with the latest edit to the question, it appears that you're missing two things:
- use a
[PSCustomObject]
type for the item being added to the combobox - set the
DisplayMember
property of the combobox to the property that you want to show
For example:
foreach ($database in $DBArray) {
$info = $database.split("|")
if ($database -ne 'SQLServer|DBName|TableName') {
$combo.Items.add([PSCustomObject]@{
value = $info
display = "CDC Enabled for $($info[2])?"
})
}
}
$combo.DisplayMember = 'display'