I am enhancing a previously written VB.NET WIndows forms application.
In one of the forms, there is a DataGridView populated from a stored procedure at Form Load.
If the user has the privileges, when the user right clicks on a record in the datagridview, I want to show a context menu allowing the user to delete the record.
Here is my code:
Private Sub m_SetEnabledContextMenu()
' for Delete record
If Not objUser.HasAuthority("Delete Record") Then
Me.DataGridView1.ContextMenu = Nothing
Me.mnuContextEquationSubmission.Enabled = False
Else
' Me.DataGridView1.ContextMenu = Me.mnuContextEquationSubmission
Me.mnuContextEquationSubmission.Enabled = True
End If
'Rest is not problem
End Sub
Private Sub DataGridView1_CellMouseDown(ByVal sender As Object, _
ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) _
Handles DataGridView1.CellMouseDown
If e.Button = System.Windows.Forms.MouseButtons.Right Then
For Each row As DataGridViewRow In DataGridView1.SelectedRows
row.Selected = False
Next
DataGridView1.Rows(e.RowIndex).Selected = True
'MessageBox.Show("DataGridView1_CellMouseDown on row " & e.RowIndex.ToString)
m_intSelRow = e.RowIndex
m_intSelCol = e.ColumnIndex
m_strRecordID = DataGridView1.Rows(e.RowIndex).Cells(0).Value
'mnuContextEquationSubmission.Show(DataGridView1, e.Location)
mnuContextEquationSubmission.Show(CType(sender, Control), e.Location)
End If
End Sub
as you can see, in the procedure 'm_SetEnabledContextMenu' I determine whether of not the user will have the authority to delete records, and thus the context menu will be activated (or at least, that's what I want) - whilst of the user doesn't have the authority, the menu should be invisible and disabled.
In the event handler DataGridView1_CellMouseDown, if it's a right-click and if the user has clicked in a data row, then I want the context menu to display where the mouse is, NOT at the top!