I am having trouble creating a "SelectAll" checkbox column that actually selects all checkboxes in a ROW not a column. The "SelectALL" column is the third column in the table that i would like to check all the boxes after it in the same ROW. The column names that follow the "SelectALL" column are dynamically generated so the column names are unknown prior to table generation. Here is my code so far:
$CheckAll_click = {
for($i=0;$i -lt $DGV1.RowCount;$i++){
if($DGV1.Rows[$i].Cells['SelectAll'].Value -eq $true) {
for($j=3;$j -le $DGV1.ColumnCount;$j++){
($DGV1.Rows[$i].Cells | ?{$_.ColumnIndex -eq $j}).Value=$true
}
}
else {
for($j=3;$j -le $DGV1.ColumnCount;$j++){
($DGV1.Rows[$i].Cells | ?{$_.ColumnIndex -eq $j}).Value=$false
}
}
}
This was harder than I expected. The trick (from here) is to trigger CommitEdit
before trying to read the state of the SelectAll checkbox. $Sender
and $EventArgs
(shortened to $e
below for readability) can be helpful parameters when you're trying to find out which checkbox was checked.
@("System.Windows.Forms","System.Drawing") | %{[reflection.assembly]::LoadWithPartialName($_) | Out-Null}
$form = New-Object System.Windows.Forms.Form -Property @{Size=New-Object System.Drawing.Size(900,600)}
$dataGridView = New-Object System.Windows.Forms.DataGridView -Property @{Anchor = "Left,Right,Top,Bottom";Size='870,550'}
@('SelectAll','Col1','Col2') | %{
$dataGridView.columns.Add( (New-Object Windows.Forms.DataGridViewCheckBoxColumn -Property @{Name=$_; TrueValue=$true; FalseValue=$false})) | Out-Null
}
1..4 | %{
$dataGridView.Rows.Add((New-Object System.Windows.Forms.DataGridViewRow)) | Out-Null
}
$dataGridView.add_CellContentClick({param($sender,$e)
if($dataGridView.Rows[$e.RowIndex].Cells[$e.ColumnIndex].OwningColumn.HeaderText -ne 'SelectAll'){return}
[Windows.Forms.DataGridViewCheckBoxCell] $ChkSelectAll = $dataGridView.Rows[$e.RowIndex].Cells |
?{$_.OwningColumn.HeaderText -eq 'SelectAll'}
$dataGridView.CommitEdit([Windows.Forms.DataGridViewDataErrorContexts]::Commit) #commits the cahnge you are editing
$dataGridView.Rows[$e.RowIndex].Cells | ? {$_.GetType().Name -eq 'DataGridViewCheckBoxCell' } | %{
$_.Value = $ChkSelectAll.Value
}
})
$form.Controls.Add($dataGridView)
$form.ShowDialog()