0

I have a CheckedListBox in Powershell. When i select some checkbox the text result is empty. When i select a second checkbox the first checkbox result text is displayed.

I use the following code for the CheckedListBox:

# Code
$ListView = New-Object System.Windows.Forms.CheckedListBox
$ListView.Location = New-Object System.Drawing.Size(10,40) 
$ListView.Size = New-Object System.Drawing.Size(533,325)
$ListView.CheckOnClick = $True
$ListView.Add_ItemCheck({
  for ($i = 0; $i - ($ListView.Items.Count-1); $i++)
  {
    if ($ListView.GetItemChecked($i))
    { 
    $s = $s + $ListView.Items[$i].ToString();
    }
  }

    Write-host $s

 })
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
questhome
  • 3
  • 4

1 Answers1

1

GetItemChecked($i) will only return the correct result for the item check that raised the event after the event handler has run.

You can inspect the event arguments for the new value of the item:

$ListView.Add_ItemCheck({

    param($sender,$e)

    $s = ""

    for ($i = 0; $i -le ($ListView.Items.Count-1); $i++)
    {
        # Check if $i is the index of the item we just (un)checked
        if($e.Index -eq $i)
        {
            # Inspect the new checked-state value
            if($e.NewValue -eq 'Checked')
            {
                $s += $ListView.Items[$i]
            }
        } 
        elseif ($ListView.GetItemChecked($i))
        { 
            # Item is already checked
            $s += $ListView.Items[$i]
        }
    }

    Write-host $s
})
Community
  • 1
  • 1
Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206