【问题标题】:Powershell: Check all checkboxes in a row where column header is unknownPowershell:选中列标题未知的行中的所有复选框
【发布时间】:2019-12-11 07:37:36
【问题描述】:

我在创建“SelectAll”复选框列时遇到问题,该列实际上选择了 ROW 中的所有复选框而不是列。 “SelectALL”列是表中的第三列,我想在同一行中选中它之后的所有框。 “SelectALL”列之后的列名是动态生成的,因此在生成表之前列名是未知的。到目前为止,这是我的代码:

$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
        }
    }
}

【问题讨论】:

    标签: winforms powershell checkbox datagridviewcheckboxcell


    【解决方案1】:

    这比我预期的要难。诀窍(来自here)是在尝试读取 SelectAll 复选框的状态之前触发CommitEdit$Sender$EventArgs(以下简称为 $e 以提高可读性)在您试图找出哪个复选框被选中时可能是有用的参数。

    @("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()
    

    【讨论】:

    • $sender 和 $e 变量在哪里设置?以及如何传递给您的单元格点击事件?
    • DataGridView.CellContentClick 事件类似于大多数 Winforms 事件,它传递接收事件的Sender 对象,以及指定所发生事件的详细信息的eEventArgs。添加 Powershell 事件处理程序时,您可以通过添加 param($sender,$e) 行来指定 $sender$e 对象。
    • 你也可以使用Powershell特有的——$this and $_automatic variables
    • 啊啊啊……灯刚亮。我在很多代码中看到了这些变量,但我总是采用它并试图“解决”这些变量,可能在构建这段代码时让我的事情变得困难两倍。非常感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2015-12-20
    • 2013-04-26
    • 2014-06-20
    • 2015-08-12
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 2019-03-16
    相关资源
    最近更新 更多