0

I am trying to figure out how to show a item as selected on a listview in a form using Visual Basic 2015. I fill in a listview on a form load, then I want to be able to use up and down buttons on the form to move through the list. I have seen almost this exact question all over the place but none of the answers work. Some of the examples given don't even show up on the IDE as choices. I am using Visual Studio 2015 IDE. Does anyone have a link or code that is more recent to go with the new Visual Basic IDE?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Yoshi
  • 1
  • 2

1 Answers1

0

Not sure if this is actually what you are looking for (or if there is a more elegant manner).

The comments are self-explanatory of what are we doing.

    ''Loading test items
    Private Sub frmTest_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.ListView1.Items.Add("Text1")
        Me.ListView1.Items.Add("Text2")
        Me.ListView1.Items.Add("Text3")
        Me.ListView1.Items.Add("Text4")
    End Sub

    ''Go up in the list
    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim intActualIndex As Integer
        If Me.ListView1.SelectedItems.Count > 0 Then  ''We check if we have a selected item
            intActualIndex = Me.ListView1.SelectedIndices.Item(0)  ''We get the actual index of the selected item
            If intActualIndex < Me.ListView1.Items.Count - 1 Then Me.ListView1.Items(intActualIndex + 1).Selected = True  ''We set the .selected=true on the next item
        End If
    End Sub

    ''Go down in the list
    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim intActualIndex As Integer
        If Me.ListView1.SelectedItems.Count > 0 Then
            intActualIndex = Me.ListView1.SelectedIndices.Item(0)
            If intActualIndex > 0 Then Me.ListView1.Items(intActualIndex - 1).Selected = True
        End If
    End Sub
El Gucs
  • 897
  • 9
  • 18
  • Thank you for your response. But I'm trying to show selected item(s) highlighted in the listview, and it seems like when you hit the button the highlight goes away. But yours works just like it should, it changes the index right, I just keep losing the highlight in the listview control. I appreciate you taking you time for me. – Yoshi Nov 26 '15 at 14:33
  • To keep the item(s) highlighted when the listview loses focus, then you need to setup the property `.HideSelection=False` – El Gucs Nov 30 '15 at 05:44