SiteMap  | About    

Delete from datagridview by Right click

There are many ways you can right click to select a row in a Datagridview and show a menu to delete it. Here we are using Datagridview CellMouseUp event to select row and contextMenuStrip1_Click event to delete the row from datagridview in

delete from gridview by right click

Select row in a dataGridView by Right click

First you should drag a contextMenuStrip from your toolbox to your form. Then you create a contextMenuStrip item "Delete Row" .

datagridview right click menu

How can I select a row in datagridview when i press right clcik

When press the right button, first thing is to find the selected row index and then show the contextMenuStrip. From the event CellMouseUp of dataGridView to indentify the row index and show the menu item. A global variable rowIndex is assigned the row index value for later delete this row.

We can delete the selected row in the contextMenuStrip1_Click event by using the global rowIdex value.

right click and delete

Public Class Form1

    Private rowIndex As Integer = 0

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim dt As New DataTable()
        dt.Columns.Add("Id", GetType(Integer))
        dt.Columns.Add("Publisher Name", GetType(String))
        dt.Columns.Add("Book", GetType(String))

        For i As Integer = 1 To 10
            dt.Rows.Add(i, "PubName" & i, "Book" & i)
        DataGridView1.DataSource = dt
        Me.DataGridView1.RowsDefaultCellStyle.BackColor = Color.Bisque
        Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Beige
    End Sub

    Private Sub DataGridView1_CellMouseUp_1(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellMouseEventArgs) Handles DataGridView1.CellMouseUp
        If e.Button = MouseButtons.Right Then
            Me.DataGridView1.Rows(e.RowIndex).Selected = True
            Me.rowIndex = e.RowIndex
            Me.DataGridView1.CurrentCell = Me.DataGridView1.Rows(e.RowIndex).Cells(1)
            Me.ContextMenuStrip1.Show(Me.DataGridView1, e.Location)
        End If
    End Sub

    Private Sub ContextMenuStrip1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ContextMenuStrip1.Click
        If Not Me.DataGridView1.Rows(Me.rowIndex).IsNewRow Then
        End If
    End Sub
End Class (C) 2018    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.