auto scroll through listbox

ud2008

Well-known member
Joined
Jul 5, 2010
Messages
148
Programming Experience
Beginner
In a listbox I have items that I want to display in a label.

I've made it sofar that I can scroll through the list using timer.

But I want when the end of the list is reached the selectedindex should return to the first item (or different if set).
Now it stops at the end and gives an error:

InvalidArgument=Value of '4' is not valid for 'SelectedIndex'.
Parameter name: SelectedIndex


This is the code I use (timer1_tick):
VB.NET:
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
            With ListBox1
                If .SelectedIndex >= 0 Then
                    .SelectedIndex += 1
                ElseIf .SelectedIndex = .Items.Count - 1 Then
                    .SelectedIndex = 0
                End If
            End With
    End Sub

The code of the listbox_selectedindexchanged:
VB.NET:
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
        Label2.Text = ListBox1.SelectedItem
        Label2.Font = My.Settings.Fontpreview
        Label2.ForeColor = My.Settings.FontColor
        Label2.TextAlign = ContentAlignment.MiddleCenter
    End Sub

Code on button_click to start the auto scroll:
VB.NET:
Private Sub RadButton4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RadButton4.Click
        Dim time2 As Single
        Time2 = TextBox1.Text
        If Me.RadButton4.ButtonElement.ButtonFillElement.BackColor = Color.Orange Then
            Me.RadButton4.ButtonElement.ButtonFillElement.BackColor = Color.Transparent
        Else
            Me.RadButton4.ButtonElement.ButtonFillElement.BackColor = Color.Orange
            ListBox1.SelectedIndex = 0
            Timer1.Interval = time2 * 1000
            Timer1.Enabled = True
            RadButton5.Enabled = True
        End If
    End Sub

Any help would be great.
 
Your SelectedIndex code logic is flawed, and is what causes the error. You seem to understand that indexes are 0 to (count-1), so what happens in your Timers event if you have 4 items and current SelectedIndex is 3 ?
 
thanks, but how do I make it logic?

if the selectedindex is equal or greater than 0, the selecteditem will forward after an amount of time and when the last item was selected, the selection should return to the first item.
 
You want to increase SelectedIndex, but acknowledge that (count-1) is the limit. Would you say that it is possible to check if SelectedIndex has reached (count-1) in code, to avoid setting a too high value ?
 
Back
Top