【问题标题】:Powershell listbox item different value from item text?Powershell列表框项目与项目文本的值不同?
【发布时间】:2018-03-28 08:00:07
【问题描述】:

我在 C#、HTML 和 Xojo 中找到了执行此操作的方法,但在 Powershell/Windows 窗体中没有找到...

我创建了一个列表框供用户选择我们使用的软件的位置代码...虽然软件安装需要特定代码 (01-07),但我想向用户显示列表框 UI 中的实际位置.这可能吗? $listBox.Items.Add(Value="01" Text="NYC") 之类的东西?

代码见下:

$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
}

【问题讨论】:

    标签: winforms powershell listbox


    【解决方案1】:

    不了解列表框如何运作的内部工作原理,您只需制作一个哈希表来将友好名称转换为数字以供软件安装。

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

    然后你可以将友好名称添加到列表框中,然后在安装软件时引用哈希表。

    [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
    }
    

    【讨论】:

    • 天才。这非常有效。太感谢了!!我的 Google-Fu 让我两手空空。
    猜你喜欢
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 1970-01-01
    • 2014-09-28
    相关资源
    最近更新 更多