Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello everyone (:


how I can use a selectedIndex in a listview?

previously I create a playlist a listbox in visual basic but eventually decided to change it for a listview but have trouble doing this in the last line

how I can change or use the selectedIndex in a listview?

What I have tried:

VB
Private Sub ListaDeReproduccionToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ListaDeReproduccionToolStripMenuItem.Click
        On Error Resume Next
        ListView1.Items.Clear()
        OpenFileDialog1.Filter = "Lista de Reproducción (*.mpl4)|*.mpl4"
        OpenFileDialog1.ShowDialog()
        Dim rutaFichero As String
        rutaFichero = OpenFileDialog1.FileName
        If IO.File.Exists(rutaFichero) = True Then
            Dim fichero As New IO.StreamReader(rutaFichero)
            While (fichero.Peek() > -1)
                ListView1.Items.Add(fichero.ReadLine)
            End While
            fichero.Close()
        End If
        Me.ListView1.SelectedIndex = Me.ListView1.SelectedIndex + 1 'line where the error appears me'
    End Sub
Posted
Updated 8-Jun-16 22:08pm
v2
Comments
Sinisa Hajnal 9-Jun-16 4:02am    
First of all, you're using VB.NET, not VB, so remove On Error Resume Next. Instead add exception handling

Second, you didn't say WHAT error do you get? Is your selected index even set? If it is, is it already last index (so that +1 throws OutOfRangeException)?
Jörgen Andersson 9-Jun-16 4:31am    
He doesn't get an error, he's using "On Error Resume Next", ;-)
Sinisa Hajnal 9-Jun-16 6:10am    
LOL! :)

1 solution

First things first: get rid of On Error Resume Next - it's an abortion which hides problems until they become too big to ignore any more. If you don't detect the errors early, they grow and grow, until you have no idea what actually caused it.
Second, get rid of the stream reader and loop, and use File.ReadAllLines and ListView.Items.AddRange instead to do it in one operation.
But trying to set the SelectedIndex of a ListView you just emptied and refilled based on the "current value" (which is probably negative by this stage) is an odd idea - I'd say you should just check the ListView contains items, and if so set it to zero.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900