VB.NET ListView - ContextMenu - Right Click To Delete


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.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post