$Form = New-Object System.Windows.Forms.Form
$Form.Text = "testform"
$Form.Size = New-Object System.Drawing.Size(250,300)
$Form.StartPosition = "Centerscreen"
$button = New-Object System.Windows.Forms.Button
$button.Location = New-Object System.Drawing.Size(50,100)
$button.Size = New-Object System.Drawing.Size(140,30)
$button.Text = "Click Here"
$button.Add_Click({[void] $form1.ShowDialog()})
$Form.controls.Add($button)
$form1 = New-Object System.Windows.Forms.Form
$form1.Size = New-Object System.Drawing.Size(500,600)
$Form1.Text = "Select row by checking checkbox test"
$dataGridView = New-Object System.Windows.Forms.DataGridView
$dataGridView.Size=New-Object System.Drawing.Size(400,500)
$form1.Controls.Add($dataGridView)
$dataGridView.ColumnCount = 2
$dataGridView.ColumnHeadersVisible = $true
$dataGridView.Columns.Insert(0, (New-Object System.Windows.Forms.DataGridViewCheckBoxColumn))
$dataGridView.Columns[0].Name = "select"
$dataGridView.Columns[1].Name = "column1"
$dataGridView.Columns[2].Name = "column2"
$dataGridView.Rows.Add($null, "test", "test2")
$dataGridView.Rows.Add($null, "test3", "test4")
$dataGridView.AllowUserToAddRows = $false
$dataGridView.AllowUserToDeleteRows = $false
$dataGridView.Columns["column1"].ReadOnly = $true
$dataGridView.Columns["column2"].ReadOnly = $true
[void] $Form.ShowDialog()
这只是创建一个带有一列复选框的datagridview,我想要的是当选中一个复选框时,相应的行被选中并高亮显示,但我不知道如何实现。
答案 0 :(得分:3)
要突出显示一行,您只需将Selected
属性设置为$ true:
$dataGridView.Rows[$n].Selected = $true
要在选中复选框时执行此操作,我们需要添加一些代码来处理相应事件发生时的选择。
根据DataGridView.CellClick
事件的文件(强调添加):
对于 DataGridViewCheckBoxCell 中的点击,此事件发生在。之前 复选框更改值,因此如果您不想计算 基于当前值的预期值,您通常会处理 而是改为 DataGridView.CellValueChanged 事件。因为那件事 仅在提交用户指定的值时才会发生 通常在焦点离开细胞时发生,你也必须处理细胞 DataGridView.CurrentCellDirtyStateChanged事件。在那个处理程序中,如果 当前单元格是一个复选框单元格,调用DataGridView.CommitEdit 方法并传递Commit值。
因此,我们可以简单地调整DataGridView.CurrentCellDirtyStateChanged
事件的文档页面中的示例:
$dataGridView.Add_CurrentCellDirtyStateChanged({
param($Sender,$EventArgs)
if($Sender.IsCurrentCellDirty){
$Sender.CommitEdit([System.Windows.Forms.DataGridViewDataErrorContexts]::Commit)
}
})
$dataGridView.Add_CellValueChanged({
param($Sender,$EventArgs)
if($EventArgs.ColumnIndex -eq 0){
$Sender.Rows[$EventArgs.RowIndex].Selected = [bool]$Sender.Rows[$EventArgs.RowIndex].Cells[$EventArgs.ColumnIndex].Value
}
})
如果要保留多行Selected
,请改为循环每一行:
$dataGridView.Add_CellValueChanged({
param($Sender,$EventArgs)
if($EventArgs.ColumnIndex -eq 0){
foreach($RowIndex in 0..($Sender.Rows.Count - 1)){
$Sender.Rows[$RowIndex].Selected = [bool]$Sender.Rows[$RowIndex].Cells[$EventArgs.ColumnIndex].Value
}
}
})
$dataGridView.MultiSelect = $true
$dataGridView.SelectionMode = [System.Windows.Forms.DataGridViewSelectionMode]::FullRowSelect