VB.NET ListView - ContextMenu - Right Click To Delete

July 13, 2017 Oclemy VB.NET ListView, VB.NET ContextMenu 1 minute, 10 seconds

Here we explore vb.net listview with context menu.We populate our listview with data.When a single row is selected and right-clicked,a context menu is displayed in our listview with delete option.When we click delete,dummy data gets deleted from our listview.

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        'SET LISTVIEW PROPERTIES
        ListView1.View = View.Details
        ListView1.FullRowSelect = True

        'CONSTRUCT COLUMNS
        ListView1.Columns.Add("Name", 150)
        ListView1.Columns.Add("Position", 150)
        ListView1.Columns.Add("Team", 150)

    End Sub

    Private Sub Populate()
        ListView1.Items.Clear()

        'ROW ARRAY
        Dim row As String() = New String() {"Jones", "Defender", "Man Utd"}
        Dim item As New ListViewItem(row)

        ListView1.Items.Add(item)

        row = New String() {"Smalling", "Defender", "Man Utd"}
        item = New ListViewItem(row)
        ListView1.Items.Add(item)

        row = New String() {"Ramsey", "Midfielder", "Arsenal"}
        item = New ListViewItem(row)

        ListView1.Items.Add(item)

        row = New String() {"Terry", "Defender", "Chelsea"}
        item = New ListViewItem(row)

        ListView1.Items.Add(item)

    End Sub

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

    Private Sub ListView1_MouseUp(sender As Object, e As MouseEventArgs) Handles ListView1.MouseUp
        'CHECK IF USER HAS RIGHT CLICKED
        If e.Button = Windows.Forms.MouseButtons.Right Then
            ContextMenuStrip1.Show(ListView1, e.Location)
        End If
    End Sub

    'DELETE ROW
    Private Sub DeleteToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DeleteToolStripMenuItem.Click
        ListView1.SelectedItems(0).Remove()
    End Sub
End Class

Best Regards.

Comments