右键单击上下文菜单以选择整行

时间:2017-03-30 13:40:50

标签: vb.net

  Private Sub dgvDisplay_CellMouseDown(sender As Object, e As DataGridViewCellMouseEventArgs) Handles dgvDisplay.CellMouseDown
        'If e.Button = Windows.Forms.MouseButtons.Right Then
        '    If e.RowIndex < 0 Or e.ColumnIndex < 0 Then Exit Sub
        '    dgvDisplay.CurrentCell = dgvDisplay(e.ColumnIndex, e.RowIndex)
        '    ' Maybe modify the text on your context menu options here?
        'Else
        '    ContextMenuStrip1.Hide()
        'End If

    End Sub

我希望只有当用户点击一个单元格并占据整行时才能显示上下文菜单,否则什么也不做,并且不显示上下文菜单选项的事件

1 个答案:

答案 0 :(得分:0)

简单的答案是设置选择模式:

dgvDisplay.SelectionMode = DataGridViewSelectionMode.FullRowSelect

如果您不想要模式并且需要在MouseDown事件中执行此操作,请尝试这样:

Private Sub dgvDisplay_CellMouseDown(sender As Object, _
                                     e As DataGridViewCellMouseEventArgs) _
                                     Handles dgvDisplay.CellMouseDown
  If e.Button = MouseButtons.Right Then
    Dim cell As DataGridViewCell = dgvDisplay.Rows(e.RowIndex).Cells(e.ColumnIndex)
    If cell.Value IsNot Nothing AndAlso Not String.IsNullOrEmpty(cell.Value.ToString) Then
      dgvDisplay.ClearSelection()
      For i As Integer = 0 To dgvDisplay.Columns.Count - 1
        dgvDisplay.Rows(e.RowIndex).Cells(i).Selected = True
      Next
      ContextMenuStrip1.Show(dgvDisplay, dgvDisplay.PointToClient(Cursor.Position))
    End If
  End If
End Sub

为了选择多个单元格,需要将MultiSelect属性设置为true。