Search code examples
vb.netcountselecteditemlistboxitemselectedindex

mixing .selectindex and .selectitem how to detect negative values for loop


I have 1 PictureBox, 1 ListBox to select a file (filename), 1 specific path (lastfoldr), it load images correctly and changes to the next and previous images, but im trying to make a loop of the images when the user try to change to the next image when is at last photo.

Private Sub ShowPrevImage()
    ListBox5.SelectedIndex = -1
    'If ListBox5.SelectedIndex < 1 Then 'here is the problem
    '    ListBox5.SelectedIndex = ListBox5.Items.Count - 1
    'End If
    Me.PictureBox1.Image = Image.FromFile(lastfoldr & (ListBox5.SelectedItem))
End Sub

Private Sub ShowNextImage()
    ListBox5.SelectedIndex = +1
  '  If ListBox5.SelectedIndex > ListBox5.Items.Count Then 'here is the problem too
   '     ListBox5.SelectedIndex = 0
   ' End If
    Me.PictureBox1.Image = Image.FromFile(lastfoldr & (ListBox5.SelectedItem)) 
end if

Solution

  • Your ListBox indexes go from 0 to ListBox.Items.Count -1 so whenever you ShowNextImage check if the index equals Count-1. if yes set index back to 0

    Private Sub ShowNextImage()
        If LisBox5.SelectedIndex = ListBox5.Items.Count-1 then
            ListBox5.SelectedIndex = 0
        Else
            ListBox5.SelectedIndex +=1
        End If