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

时间:2017-09-18 16:01:19

标签: winforms powershell checkbox datagridview datagridviewcheckboxcell

我正在第一列中使用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()

例如,如果选中第二个和第四个框,它将仅报告选中第二个框并且未选中第四个框(查看暗黄色输出)。

有人能指出我为什么会发生这种情况的正确方向以及如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

使用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 
        }
    }
})

如果您想在Datagrid中阅读有关Value vs EdittedFormattedValue的更多信息 https://www.codeproject.com/Tips/777492/EditedFormattedValue-v-s-Value-in-Datagridview