自动选择下拉列表中长度最长的选项

问题描述 投票:0回答:1

我希望这个组合选择框自动突出显示列表中最长的选项。

foreach($onedriveaccount in $onedriveaccounts)
{
  $comboBox1.Items.add($onedriveaccount)
  # This loop should set the item with the longest length to $defaultcomboselect but it doesn't seem to actually pick it
  if($onedriveaccount.length -gt $defaultcombobiglen)
    {
    $defaultcomboselect=$comboBox1.items.Count
    $defaultcombobiglen=$onedriveaccount.length
    }
}

$comboBox1.SelectedItem=$defaultcomboselect
$Form1.Controls.Add($comboBox1)

我希望它自动选择最长的选项。这是自动选择下拉列表中长度最长的选项并在 30 秒后选择该选项

中的第一个问题
powershell winforms
1个回答
0
投票

分配给

.SelectedItem
是正确的,但是您分配的是整数 (
$comboBox1.items.Count
) 而不是实际项目。如果你想让它变得非常简单,首先添加项目:

foreach ($onedriveaccount in $onedriveaccounts) {
    $comboBox1.Items.Add($onedriveaccount)
}

然后使用

.Items
属性按
Length
对它们进行排序,然后选择最后一项并进行分配:

$comboBox1.SelectedItem = $comboBox1.Items | Sort-Object Length | Select-Object -Last 1

而且,如果您希望组合框中的所有项目都按长度排序(最长的项目在前),您可以:

$onedriveaccounts | Sort-Object Length -Descending | ForEach-Object {
    $comboBox1.Items.Add($_)
}

然后简单地说:

$comboBox1.SelectedItem = $comboBox1.Items[0]
© www.soinside.com 2019 - 2024. All rights reserved.