Click here to Skip to main content
15,867,765 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am having for a weird situation with a ListBox.
In a Module I fill a ListBox with names from a file. On the Form the ListBox shows 2 Items.
VB
If File.Exists(fUsers) Then
    With frmSettings
        Dim NoLines As Integer = File.ReadAllLines(fUsers).Length ' Antal linier i filen
        Dim lNames As New List(Of String)
        Dim lPass As New List(Of String)

        For i = 1 To NoLines - 1 Step 2
            lNames.Add(Crypto.Decrypt(File.ReadAllLines(fUsers).ElementAtOrDefault(i), skey))
        Next i
        For i = 2 To NoLines - 1 Step 2
            lPass.Add(Crypto.Decrypt(File.ReadAllLines(fUsers).ElementAtOrDefault(i), skey))
        Next
        For i = 0 To lNames.Count - 1
            pList.Add(New Users(lNames(i), lPass(i)))
            .lstUsers.Items.Add(lNames(i))
        Next
    End With
End If

When I click the ListBox the first name shows correctly. The second name gives me the error:
IndexOutOfRangeException was unhandled - Index was outside the bounds of the array
VB
Private Sub lstUsers_Click(sender As Object, e As System.EventArgs) Handles lstUsers.Click
    If lstUsers.Items.Count > 0 Then
        Debug.Print(CStr(lstUsers.SelectedIndex))
        Debug.Print(CStr(lstUsers.Items.Count))
        txtUser.Text = lstUsers.SelectedItems.Item(lstUsers.SelectedIndex).ToString
    End If
End Sub

Debug shows 2 items in count
When clicked Debug shows the correct Index

Thank you in advance,
Henrik
Posted
Comments
Richard MacCutchan 3-Oct-14 4:05am    
ListView index starts at 0, so if you have 2 items, the valid indices are 0 and 1.
N. Henrik Lauridsen 3-Oct-14 4:40am    
Yes that is correct, but my Debug shows Index 0 for the first item and Index 1 for the second so this should give the names right?
txtUser.Text = lstUsers.SelectedItems.Item(lstUsers.SelectedIndex).ToString

1 solution

Your error is in this:
VB
lstUsers.SelectedItems.Item(lstUsers.SelectedIndex).ToString


You have only 1 selected item (which is the one clicked) - unless you're multiselecting you should always have 0 instead of lstUsers.SelectedIndex and even when multiselecting, unless you select ALL items this will break at some point.

Or alternatively use full list to select the one selected:
VB
lstUsers.Items.Item(lstUsers.SelectedIndex).ToString


If this helps, please take time to accept the solution. Thank you.
 
Share this answer
 
v4
Comments
N. Henrik Lauridsen 3-Oct-14 7:01am    
Thank you Sinisa Hajnal, that did it. I am happy that so many are willing to help. Thank's again Henrik

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