Winforms 带有checkboxcolumn的DataGridView仅检测第一个复选框

Winforms 带有checkboxcolumn的DataGridView仅检测第一个复选框,winforms,powershell,checkbox,datagridview,datagridviewcheckboxcell,Winforms,Powershell,Checkbox,Datagridview,Datagridviewcheckboxcell,我正在处理DataGridView,第一列中有一个CheckBoxColum。我希望能够查询所有当前复选框的索引。我有这个测试代码,但出于某种原因,它只返回选中的第一个复选框,而不是所有复选框的集合 [void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”) [void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Draw

我正在处理DataGridView,第一列中有一个CheckBoxColum。我希望能够查询所有当前复选框的索引。我有这个测试代码,但出于某种原因,它只返回选中的第一个复选框,而不是所有复选框的集合

[void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Windows.Forms”)
[void] [System.Reflection.Assembly]::LoadWithPartialName(“System.Drawing”)
$form = New-Object System.Windows.Forms.Form
$form.Size = New-Object System.Drawing.Size(300, 200)
$form.KeyPreview = $true
$form.StartPosition = 'centerscreen'
$form.Add_KeyDown({if($_.KeyCode -eq "Escape"){$form.Close()}})
$DataGrid1 = New-Object System.Windows.Forms.DataGridView
$DataGrid1.Location = New-Object System.Drawing.Size(298,29)
$DataGrid1.Dock = "Fill"
$DataGrid1.BorderStyle = 'FixedSingle'
$DataGrid1.AlternatingRowsDefaultCellStyle.BackColor = 'LightGray'
$DataGrid1.AllowUserToAddRows = $false
$DataGrid1.RowHeadersVisible = $false
$CheckBoxColumn = New-object System.Windows.Forms.DataGridViewCheckBoxColumn
$CheckBoxColumn.Width = 50
$CheckBoxColumn.ReadOnly = $false
$DataGrid1.columns.Add($CheckBoxColumn) |out-null
$dataGrid1.columncount = 3

$DataGrid1.rows.Add($($false,'b','d')) |out-null
$DataGrid1.rows.Add($($false,'b','d')) |out-null
$DataGrid1.rows.Add($($false,'b','d')) |out-null
$DataGrid1.rows.Add($($false,'b','d')) |out-null

$form.add_Keydown({
    if($_.KeyCode -eq 70){ # the 'f' key
        for($i = 0;$i -lt $DataGrid1.Rows.Count;$i++){
            if($DataGrid1.rows[$i].Cells[0].Value.ToString() -eq "true"){
                write-host $i -ForegroundColor Magenta #output checked indexes
            }  #output checkbox state (true = checked)
            write-host $DataGrid1.rows[$i].Cells[0].Value -BackgroundColor DarkYellow 
        }
    }
})
$form.Controls.Add($DataGrid1)
$form.ShowDialog()
例如,如果选中第二个和第四个框,它将只报告第二个框已选中,第四个框未选中。查看深黄色输出


有人能告诉我为什么会发生这种情况以及如何解决它吗?

请改用EditedFormattedValue

$form.add_Keydown({
    clear
    if($_.KeyCode -eq 70){ # the 'f' key
        for($i = 0;$i -lt $DataGrid1.Rows.Count;$i++){
            if($DataGrid1.rows[$i].Cells[0].EditedFormattedValue.ToString() -eq "True"){
                write-host $i -ForegroundColor Magenta #output checked indexesf
            }  #output checkbox state (true = checked)
            write-host $DataGrid1.rows[$i].Cells[0].EditedFormattedValue -BackgroundColor DarkYellow 
        }
    }
})
如果您想阅读更多关于数据网格中的Value vs EditedFormattedValue的内容