【问题标题】:DataGridView with checkboxcolumn only detects first checked box带有复选框列的 DataGridView 仅检测第一个复选框
【发布时间】:2018-02-27 06:01:13
【问题描述】:

我正在处理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()

例如,如果第二个和第四个框被选中,它只会报告第二个框被选中而第四个框未被选中(查看深黄色输出)。

有人可以指出为什么会发生这种情况以及如何解决它的正确方向吗?

【问题讨论】:

    标签: winforms powershell checkbox datagridview datagridviewcheckboxcell


    【解决方案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 与 EdittedFormattedValue https://www.codeproject.com/Tips/777492/EditedFormattedValue-v-s-Value-in-Datagridview

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多