Powershell: Selecting DataGridView Row

非 Y 不嫁゛ 提交于 2020-01-14 14:01:45

问题


So far I have this code.

$form = New-Object System.Windows.Forms.Form
$form.Size = New-Object System.Drawing.Size(900,600)
$dataGridView = New-Object System.Windows.Forms.DataGridView
$dataGridView.Size=New-Object System.Drawing.Size(800,400)
$go = New-Object System.Windows.Forms.Button
$go.Location = New-Object System.Drawing.Size(300,450)
$go.Size = New-Object System.Drawing.Size(75,23)
$go.text = "Select"
$form.Controls.Add($go)
$form.Controls.Add($dataGridView)


$dataGridView.ColumnCount = 4
$dataGridView.ColumnHeadersVisible = $true
$dataGridView.Columns[0].Name = "Name"
$dataGridView.Columns[1].Name = "ID"
$dataGridView.Columns[2].Name = "Description"
$dataGridView.Columns[3].Name = "Memory"

$dataGridView.Columns[0].width = 240

get-process | foreach {
    $dataGridView.Rows.Add($_.Name,$_.ID,$_.Description,$_.WorkingSet) | out-null
}

$go.Add_Click({
    $selectedRow = $dataGridView.CurrentRowIndex
write-host $selectedRow
})

[void]$form.ShowDialog() 

It simply gets the Process Name, ID, etc. properties and puts them into pre-defined headers in a DataGridView.

My problem is that I want to see the row I've clicked on via $selectedRow = $dataGridView.CurrentRowIndex and output it to the console. Instead, when the 'Select' button is pushed, a blank string is output to the terminal.


回答1:


You can also get the row index with:

$dataGridView.CurrentCell.RowIndex

or

$dataGridView.SelectedRows[0].Index

You may also want to set the grid MultiSelect property to $false. Currently it allows multiple rows selection. Another thing to consider is setting the SelectionMode property to 'FullRowSelect'. When the grid is populated the first column is selected, not the whole row.




回答2:


Change

$selectedRow = $dataGridView.CurrentRowIndex 

to

$selectedRow = $dataGridView.CurrentRow.Index


来源:https://stackoverflow.com/questions/11493700/powershell-selecting-datagridview-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!