Visual Basic: Right-click a DataGridView cell and provide a context menu of options for filling the cell

Platform:Visual Basic
Task:Right-click a DataGridView cell and provide a context menu of options for filling the cell
Discussion:
Normally when you right click a DataGridView the click does not set the DGV's CurrentCell to the location right clicked. The CurrentCell remains elsewhere. This makes it hard, for instance, to set up a context menu of options for filling a right clicked cell. As an example, you may want to right click a cell and have the option of calling a FolderBrowser through a ContextMenu in order to fill the cell with the path to a directory. Here is a method for right-clicking a DGV cell and setting the CurrentCell property to the right-clicked cell.
Example:
    Private Sub ProjectsDataGridView_CellMouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles ProjectsDataGridView.CellMouseClick
        'if the datagridview was right clicked, set the currentcell to the right-clicked cell and then show a context menu with options for filling the right-clicked cell
        If (e.Button = Windows.Forms.MouseButtons.Right) Then
            Try
                'highlight the right-clicked cell, make it the dgv's current cell
                ProjectsDataGridView.CurrentRow.Selected = False
                ProjectsDataGridView.Rows(e.RowIndex).Selected = True
                ProjectsDataGridView.CurrentCell = ProjectsDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex)
                'show the context menu to provide options for filling the right-clicked cell
                ctxDirectory.Show(ProjectsDataGridView, e.Location)
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try

        End If
    End Sub
Back to Index