从ListBox中选择/突出显示对象会引发错误

时间:2014-04-07 09:01:08

标签: vb.net object listbox

我有一个包含一些对象的列表框。在这种情况下" Persons",类似这样的事情:

Public Class Person
    Public ID As Integer
    Public Name As string = ""
    Public Email As string = ""

    Public Sub New(ByVal ID As Integer)
        Me.ID = ID
        GetPersonInfo()
    End Sub

    Private Sub GetPersonInfo()
        'some stuff gathering info
        Me.Name = 'From some stuff
        Me.Email= 'From some stuff
    End Sub

    Public Overrides Function ToString() As String
        Return "[" & Me.ID & "] " & Me.Name & " - " & Me.Email
    End Function

End Class

到目前为止一切顺利。当我加载表单时,我有一个循环将人员添加到列表框中,代码看起来像这样:

For Each UserId As Integer In MyUsersList
    ListBox_Users.Items.Add(New Person(UserId))
Next

这里没什么奇怪的。我得到一个很好的格式为[ID] Name - Email的人员列表。

然而,在程序的另一个地方我可以选择其他东西,比如汽车。汽车显示在ComboBox中,当我在此列表中更换汽车时,我会收集有关该汽车的信息,然后可以获取车主的电子邮件。如果列表框中列出了此电子邮件,我想自动在列表框中选择/突出显示此人员。这个代码看起来像这样:

For Each P As Person In ListBox_Users
    If P.Email = TheEmailRegistredForTheSelectedCar Then
        ListBox_Users.SelectedItem = P
    End If
Next

当我运行此代码时,我收到错误"此枚举器绑定的列表已被修改。只有在未更改列表时才能使用枚举器。"

嗯,是的,我能理解有关循环ListBox的一些蠢事,并且在这个循环中改变了它所选择的索引,但在这种情况下我该怎么做呢?

编辑:目前我想出了这个代码来选择ListBox中的Person,但感觉还有更好/更漂亮的方法吗?

Dim TempPerson As Person
TempPerson = Nothing
For Each P As Person In ListBox_Users
    If P.Email = TheEmailRegistredForTheSelectedCar Then
        TempPerson = P
    End If
Next
If TempPerson Is Nothing Then
    ListBox_Users.ClearSelected()
Else
    ListBox_Users.SelectedItem = TempPerson
End If

1 个答案:

答案 0 :(得分:1)

这应该有效。谨防sintax错误,我没试过它

dim index as integer
dim done as boolean
while not done andalso not index = ListBox_Users.items.count -1
If ListBox_Users.items(index).Email = TheEmailRegistredForTheSelectedCar Then
    done = true
else
    index +=1
End If
end while
if done then
Listbox_Users.selectedindex = index
end if