Ellery Higgins
Ellery Higgins

Reputation: 25

Powershell listbox item different value from item text?

I have found ways of doing this in C#, HTML, and Xojo, but not Powershell/Windows Forms...

I have created a Listbox for users to select a location code for software we use...while the software installation requires the specific code (01-07), I would like to show the users the actual location in the Listbox UI. Is this possible? Something like $listBox.Items.Add(Value="01" Text="NYC")?

See below for code:

$label = New-Object System.Windows.Forms.Label
$label.Location = New-Object System.Drawing.Point(10,20) 
$label.Size = New-Object System.Drawing.Size(280,20) 
$label.Text = "Please select a Location Code:"
$form.Controls.Add($label) 

$listBox = New-Object System.Windows.Forms.ListBox 
$listBox.Location = New-Object System.Drawing.Point(10,40) 
$listBox.Size = New-Object System.Drawing.Size(150,20) 
$listBox.Height = 140

[void] $listBox.Items.Add("01")
[void] $listBox.Items.Add("02")
[void] $listBox.Items.Add("03")
[void] $listBox.Items.Add("04")
[void] $listBox.Items.Add("06")
[void] $listBox.Items.Add("07")

$form1.Controls.Add($listBox) 

$form1.Topmost = $True

$result1 = $form1.ShowDialog()

if ($result1 -eq [System.Windows.Forms.DialogResult]::OK)
{
    $Server = $listBox.SelectedItem
    $Server
}

Upvotes: 0

Views: 2175

Answers (1)

TheMadTechnician
TheMadTechnician

Reputation: 36332

Short of looking into the inner workings of how a listbox functions, you could just make a hashtable to convert friendly names to numbers for the software installation.

$locHash = @{
    'NYC' = '01'
    'Chicago' = '02'
    'LA' = '03'
    'Seattle' = '04'
    'Orlando' = '05'
    'Dallas' = '06'
}

Then you can add the friendly names to the listbox, and just reference the hashtable when you go to install the software.

[void] $listBox.Items.Add("NYC")
[void] $listBox.Items.Add("Chicago")
[void] $listBox.Items.Add("LA")
[void] $listBox.Items.Add("Seattle")
[void] $listBox.Items.Add("Orlando")
[void] $listBox.Items.Add("Dallas")
$form1.Controls.Add($listBox) 

$form1.Topmost = $True

$result1 = $form1.ShowDialog()

if ($result1 -eq [System.Windows.Forms.DialogResult]::OK)
{
    $Server = $locHash[$listBox.SelectedItem]
    $Server
}

Upvotes: 1

Related Questions