Home > front end >  How do you create a Powershell boolean Calculated Property with a value that can be recognised by a
How do you create a Powershell boolean Calculated Property with a value that can be recognised by a

Time:12-31

During retrieval of a larger data set, I am trying to create a calculated property called 'Checked' in Powershell, with an initial value of $false:

$var = [System.Collections.ArrayList](@($dataSource | Select-Object -Unique -Property @{Name='Checked';Expression={$false}},ID,Name))

This is then visualised in a WinForm DataGridView object, generated from Powershell:

$bAnalysesDataGrid                       = [System.Windows.Forms.DataGridView]::new()
$bAnalysesDataGrid.location              = [System.Drawing.Size]::new((20*$w),(210*$h))
$bAnalysesDataGrid.width                 = 1960*$w
$bAnalysesDataGrid.height                = 600*$h

[void]$bAnalysesDataGrid.Columns.Add([System.Windows.Forms.DataGridViewCheckBoxColumn]::new())
[void]$bAnalysesDataGrid.Columns.Add([System.Windows.Forms.DataGridViewTextBoxColumn]::new())
[void]$bAnalysesDataGrid.Columns.Add([System.Windows.Forms.DataGridViewTextBoxColumn]::new())
$bAnalysesDataGrid.Columns[0].Name             = "Checked"
$bAnalysesDataGrid.Columns[0].DataPropertyName = "Checked"
$bAnalysesDataGrid.Columns[1].Name             = "ID"
$bAnalysesDataGrid.Columns[1].DataPropertyName = "ID"
$bAnalysesDataGrid.Columns[2].Name             = "Name"
$bAnalysesDataGrid.Columns[2].DataPropertyName = "Name"

$bAnalysesDataGrid.DataSource = $var

However, when the 'Checked' property loads into the first column, the following error appears, which suggests the $false is being received as a String:

The following exception occurred in the DataGridView: System.FormatException: Value 'False' cannot be converted to type 'Boolean'.

How can I create a calculated property that works with the CheckBox, to start with a value of $false? I've tried various combinations of zeroes, strings and $ signs, none of which seems to behave correctly.

Full error message:

Exception

CodePudding user response:

The data binding logic in Windows Forms doesn't quite know how to invoke PowerShell's extended properties correctly, so calculated properties, note properties or [pscustomobject] members won't work well with this approach.

Instead, use the class keyword to define a real .NET type, and member binding should then work:

class CheckableDataRow {
  [bool]$Checked
  [int]$ID
  [string]$Name
}

# fetch/construct data rows
$vars = $dataSource | Select-Object -Unique -Property @{Name='Checked';Expression={$false}},ID,Name 

# convert to CheckableDataRow's
$vars = $vars -as [CheckableDataRow[]]

# rest of the script remains the same...
  • Related