Page 1 of 1

Checked Listbox

Posted: Thu Mar 09, 2017 8:51 am
by timstspry17
Product, version and build: PowerShell Studio 2017, 5.4.136
(*** Please do not write "latest" as a version, specify a version number ***)
32 or 64 bit version of product: 64 bit
Operating system: Windows 10
32 or 64 bit OS: 64 bit
PowerShell Version: V5

I am using the Checked Listbox, but don't know how to set the checkbox to checked when I add elements to the listbox? Any help would be appreciated!

Re: Checked Listbox

Posted: Thu Mar 09, 2017 9:00 am
by DevinL
[TOPIC MOVED TO POWERSHELL GUIS FORUM BY MODERATOR]

Re: Checked Listbox

Posted: Thu Mar 09, 2017 9:01 am
by DevinL
Simply call the $checkedListBox.SetItemChecked() method like so:
  1. $checkedlistbox1.SetItemChecked(0, $true)
Now the very first item in the ListBox will be checked.

Re: Checked Listbox

Posted: Thu Mar 09, 2017 9:32 am
by jvierra
It might be easier to do this:
  1. $checkedlistbox1.Items.Add('My Item',$true)
You can also use data binding to set the checked state to a property in the data source object.

Re: Checked Listbox

Posted: Thu Mar 09, 2017 10:52 am
by DevinL
Oh, I didn't even know that was an available method.

Thanks, Jvierra.

Re: Checked Listbox

Posted: Thu Mar 09, 2017 11:03 am
by jvierra
Devin - there are many methods and approaches. The MSDN docs are a very good place to get all of the options. I always review them repeatedly when wantig to do something new with a control. Eventually it all sticks.

The one weakness of the CheckedListBox is that it does not support full data binding as most other control do. There is a replacement on CodePlex that adds databinding for the checkbox.

We can also do the following to bind to the "DataSource".
  1. $form1_Load={
  2.    
  3.     $path = 'd:\test'
  4.     $files = Get-ChildItem $path -File |
  5.         Select Name,@{n='Oversize';e={if($_.Length -gt 1Kb){'Checked'}else{'Unchecked'}}}
  6.     $dt = ConvertTo-DataTable $files
  7.    
  8.     $checkedlistbox1.DataSource = $dt
  9.     $checkedlistbox1.DisplayMember = 'Name'
  10.     $checkedlistbox1.ValueMember = 'Oversize'
  11.    
  12.     #sync data
  13.     (0 .. ($checkedlistbox1.Items.Count-1)) |
  14.         ForEach-Object{
  15.             $checkedlistbox1.SetItemCheckState($_, $checkedlistbox1.Items[$_].Oversize)
  16.         }
  17. }