ListBox IndexOutOfRangeException未处理OnClick [英] ListBox IndexOutOfRangeException was unhandled OnClick

查看:58
本文介绍了ListBox IndexOutOfRangeException未处理OnClick的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我在使用ListBox时遇到了奇怪的情况。

在一个模块中,我用一个名字来填充一个ListBox一份文件。在表单上,​​ListBox显示2个项目。

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.

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



单击ListBox时,第一个名称显示正确。第二个名称给出了错误:

IndexOutOfRangeException未处理 - 索引超出了数组的范围

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



调试显示计数中的2项

单击时调试显示正确的索引



提前谢谢,

Henrik


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

Thank you in advance,
Henrik

推荐答案

你的错误是这样的:

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





你只有一个选中的项目(点击一个) - 除非你多选,你应该总是有0而不是lstUsers.Selecte dIndex甚至在多选时,除非你选择所有项目,否则会在某些时候中断。



或者使用完整列表选择所选项:



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:

lstUsers.Items.Item(lstUsers.SelectedIndex).ToString





如果这有帮助,请花时间接受解决方案。谢谢。



If this helps, please take time to accept the solution. Thank you.


这篇关于ListBox IndexOutOfRangeException未处理OnClick的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆