Powershell CheckedListBox check if in string / array

孤街醉人 提交于 2019-12-24 01:56:18

问题


I've started learning Powershell and am now stuck after spending several hours on a problem I can find solutions for in multiple languages except Powershell.

I need to place a check against each item in a CheckedListBox that matches any of the values in a semi-colon delimited string named $MLBSVar_SelectedPackages. (eg. $MLBSVar_SelectedPackages = 'packageA;packageB;packageC;') and so on.

I've come up with this line but it doesn't yet work. Please can you help me?

if ($MLBSVar_SelectedPackages -ne $null) { 
    ForEach ($PackageName in $MLBSVar_SelectedPackages) { 
        ForEach ($item in $clb_SC_AvailablePackages.Items) { 
            if ($item -eq $PackageName) { 
                $clb_SC_AvailablePackages.Item($PackageName).Checked = $true 
            }
        }
    }
}

I've also tried .SetItemCheckState([System.Windows.Forms.CheckState]::Checked) in place of .Checked. The (one) issue seems to be getting a handle on the list item in the final section as it seems to be passed as a string rather than object? I have a VBS background and would really appreciate the assistance.


回答1:


I think what you're looking for is something like the following code. You can use the SetItemChecked() method of the CheckedListBox class to check an item at a particular index. I see that you have attempted to use SetItemCheckState(), but did not make mention of SetItemChecked().

# Import Windows Forms Assembly
Add-Type -AssemblyName System.Windows.Forms;
# Create a Form
$Form = New-Object -TypeName System.Windows.Forms.Form;
# Create a CheckedListBox
$CheckedListBox = New-Object -TypeName System.Windows.Forms.CheckedListBox;
# Add the CheckedListBox to the Form
$Form.Controls.Add($CheckedListBox);
# Widen the CheckedListBox
$CheckedListBox.Width = 350;
$CheckedListBox.Height = 200;
# Add 10 items to the CheckedListBox
$CheckedListBox.Items.AddRange(1..10);

# Clear all existing selections
$CheckedListBox.ClearSelected();
# Define a list of items we want to be checked
$MyArray = 1,2,5,8,9;

# For each item that we want to be checked ...
foreach ($Item in $MyArray) {
    # Check it ...
    $CheckedListBox.SetItemChecked($CheckedListBox.Items.IndexOf($Item), $true);
}

# Show the form
$Form.ShowDialog();

After running this code, you should be presented with a dialog that looks similar to the following screenshot.



来源:https://stackoverflow.com/questions/21008294/powershell-checkedlistbox-check-if-in-string-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!