vb.net DataGridView 选择行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15555788/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 12:55:02 来源:igfitidea点击:
DataGridView select Row
提问by user2195966
I want to select a row in my DataGridView with a right click. But with my current code I first have to click on the row with a regular left mouse click.
我想通过右键单击在我的 DataGridView 中选择一行。但是对于我当前的代码,我首先必须通过常规的鼠标左键单击来单击该行。
Is there any way to select the current row with a right click and than open a ContextMenuStrip?
有没有办法通过右键单击选择当前行而不是打开 ContextMenuStrip?
Private Sub DataGridView1_CellMouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDown
If e.Button = Windows.Forms.MouseButtons.Right AndAlso e.RowIndex >= 0 Then
Me.DataGridView1.CurrentCell = Me.DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex)
End If
End Sub
Private Sub datagridview1_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles DataGridView1.MouseDown
If e.Button = Windows.Forms.MouseButtons.Right Then
Dim hti As DataGridView.HitTestInfo = sender.HitTest(e.X, e.Y)
If hti.Type = DataGridViewHitTestType.Cell Then
If Not DataGridView1.Rows(hti.RowIndex).Selected Then
DataGridView1.ClearSelection()
DataGridView1.Rows(hti.RowIndex).Selected = True
End If
End If
End If
End Sub
采纳答案by Rob
Try this:
尝试这个:
Private Sub DataGrid1_CellMouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
On Error Resume Next
If e.Button = MouseButtons.Right Then
'Clear previous selections
For x As int32 = 0 To ds.Tables(0).Rows.Count() - 1
DataGrid1.UnSelect(x)
Next x
'select row under mouse click
Dim info As DataGrid.HitTestInfo = DataGrid1.HitTest(e.X, e.Y)
If info.Row > -1 Then
DataGrid1.CurrentRowIndex = info.Row
DataGrid1.Select(info.Row)
Application.DoEvents()
DataGridContextMenu.Show(Cursor.Position)
End If
info = Nothing
End If
End Sub

