2016-10-06 100 views
0

嗯,你好!這裏有一個關於我的代碼的簡短問題。我試圖打開一個上下文菜單時,我右鍵單擊我的DataGridView中的單元格。這是我有:在DataGridView上打開上下文菜單

Private Sub DataGridView1_CellMouseClick(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseClick 
    If e.Button = Windows.Forms.MouseButtons.Right Then 
     If e.ColumnIndex = -1 = False And e.RowIndex = -1 = False Then 
      Me.DataGridView1.ClearSelection() 
      Me.DataGridView1.CurrentCell = Me.DataGridView1.Item(e.ColumnIndex, e.RowIndex) 
      DataGridView1.ContextMenuStrip = mnuCell 
     End If 
    End If 
End Sub 

不幸的是,當我第一次右鍵單擊該程序時,它不會立即打開上下文菜單。它只選擇單元格。但是如果我再次右擊它,它將打開上下文菜單。

我的第二個問題是,如果我右鍵點擊另一個單元格,上下文菜單仍然打開,它不會選擇我右鍵單擊的其他單元格。我究竟做錯了什麼?

回答

0

上下文菜單將在CellMouseClick事件觸發前彈出,因此請將代碼移至CellMouseDown。

Private Sub DataGridView1_CellMouseDown(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseDown 
    If e.Button = Windows.Forms.MouseButtons.Right Then 
     If e.ColumnIndex <> -1 And e.RowIndex <> -1 Then 
      Me.DataGridView1.ClearSelection() 
      Dim cell = Me.DataGridView1.Item(e.ColumnIndex, e.RowIndex) 
      Me.DataGridView1.CurrentCell = cell 
      cell.Selected = True 'Needed if you right click twice on the same cell 
      DataGridView1.ContextMenuStrip = mnuCell 
     End If 
    End If 
End Sub 
+0

哦,對,因爲MouseClick事件包括鼠標上下。哇,永遠不會發現我自己。謝謝! :) – rsprodftw1