VB.NET DataGridView - ContextMenu - Right Click To Delete

July 6, 2017 Oclemy VB.NET DataGridView, VB.NET ContextMenu 1 minute, 19 seconds

we see how to work with datagridview component and ContextMenu.We have data in our datagridview.When  we right click,the row gets selected and a contextmenu with delete option is shown.When we select delete,the items gets deleted from datagridview.

Public Class Form1
    Dim index As Integer = 0

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'CONSTRUCT DATAGRIDVIEW
        DataGridView1.ColumnCount = 3
        DataGridView1.Columns(0).Name = "Name"
        DataGridView1.Columns(1).Name = "Position"
        DataGridView1.Columns(2).Name = "Team"

    End Sub

    'POPULATE DGVIEW WITH DATA
    Private Sub Populate()
        Dim row As String() = New String() {"Remy", "Striker", "Chelsea"}
        DataGridView1.Rows.Add(row)

        row = New String() {"Teryy", "Defender", "Chelsea"}
        DataGridView1.Rows.Add(row)
        row = New String() {"Walcott", "Winger", "Arsenal"}
        DataGridView1.Rows.Add(row)
        row = New String() {"Kompany", "Defender", "Man City"}
        DataGridView1.Rows.Add(row)
        row = New String() {"Jones", "Defender", "Man Utd"}
        DataGridView1.Rows.Add(row)
    End Sub

    Private Sub DataGridView1_CellMouseUp(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseUp
        'RIGHT CLICKS
        If e.Button = Windows.Forms.MouseButtons.Right Then

            DataGridView1.Rows(e.RowIndex).Selected = True
            index = e.RowIndex
            DataGridView1.CurrentCell = DataGridView1.Rows(e.RowIndex).Cells(1)
            ContextMenuStrip1.Show(DataGridView1, e.Location)
            ContextMenuStrip1.Show(Cursor.Position)
        End If

    End Sub

    Private Sub ContextMenuStrip1_Click(sender As Object, e As EventArgs) Handles ContextMenuStrip1.Click
        'CHECK IF NEW ROW
        If Not DataGridView1.Rows(index).IsNewRow Then
            DataGridView1.Rows.RemoveAt(index)
        End If
    End Sub

    Private Sub populateBtn_Click(sender As Object, e As EventArgs) Handles populateBtn.Click
        Populate()
    End Sub

    Private Sub clearBtn_Click(sender As Object, e As EventArgs) Handles clearBtn.Click
        DataGridView1.Rows.Clear()
    End Sub
End Class

Best Regards.

Comments