mdsailing
mdsailing

Reputation: 123

Index Selection in ListView created at runtime in Visual Basic (Visual Studio 2019)

I am trying to use a ListView box created at runtime and I am able to populate items but the SelectedIndexChanged event is not working. I know I am missing something really simple. Below is a minimal working example where I am creating the ListView on a button click and populating with a couple of items. When I select an item nothing happens in the SelectedIndexChanged event.

Public Class Form1

    Dim lstMylist As ListView

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        lstMylist = New ListView()
        lstMylist.Location = New Point(37, 312)
        lstMylist.Size = New Size(150, 150)
        Me.Controls.Add(lstMylist)
        lstMylist.View = View.SmallIcon

        Dim myListItem1 As ListViewItem
        myListItem1 = lstMylist.Items.Add("Item 1")
        Dim myListItem2 As ListViewItem
        myListItem2 = lstMylist.Items.Add("Item 2")
    End Sub

    Private Sub lstMylist_SelectedIndexChanged(sender As Object, e As EventArgs)
        MessageBox.Show("I am here")
        Select Case lstMylist.FocusedItem.Index
            Case 0
                MessageBox.Show("item 1")
            Case 1
                MessageBox.Show("item 2")
            Case Else
                MessageBox.Show("invalid")
        End Select
    End Sub

End Class

Upvotes: 2

Views: 453

Answers (2)

Steve
Steve

Reputation: 216273

You need to add the event handler to the ListView SelectedIndexChanged event

lstMylist = New ListView()
lstMylist.Location = New Point(37, 312)
lstMylist.Size = New Size(150, 150)

' Add the event handler for the listview
AddHandler lstMyList.SelectedIndexChanged, AddressOf lstMylist_SelectedIndexChanged

Me.Controls.Add(lstMylist)
lstMylist.View = View.SmallIcon

As outlined by djv it is important to call RemoveHandler if you remove the ListView

RemoveHandler lstMyList.SelectedIndexChanged, AddressOf lstMylist_SelectedIndexChanged

Upvotes: 2

djv
djv

Reputation: 15774

Steve's answer will work. But an alternative is to simply make your ListView WithEvents

Dim WithEvents lstMylist As ListView

and add Handles to the method declaration

Private Sub lstMylist_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstMylist.SelectedIndexChanged

This is more a VB.NET way of doing things. AddHandler is similar to C# Event += new EventHandler syntax.

Note, if using AddHandler, a matching RemoveHandler should appear if the ListView is to be removed and added repeatedly.

Upvotes: 1

Related Questions