2014-04-07 29 views
1

我有一個包含一些對象的列表框。在這種情況下,「人」,像這樣:從ListBox中選擇/高亮顯示對象會拋出錯誤

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的人員列表。

如何過,在程序中的其它地方,我可以選擇別的東西,像汽車,例如。汽車顯示在一個組合框中,當我在此列表中更換汽車時,我收集有關該汽車的信息,然後可以獲取車主的電子郵件。如果此電子郵件列在列表框中,我想在列表框中自動選擇/突出顯示此人。該代碼,這看起來是這樣的:

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

當我運行這段代碼,我得到的錯誤「,這枚舉綁定已被修改,只能使用一個枚舉如果列表不改變該列表。 「。

嗯,是的,我能理解有有鬼循環一個列表框,在這種循環改變其選定的索引,但我應該怎麼做正確的在這種情況下?

編輯:目前我我想出了這個代碼來選擇ListBox中的人,但感覺像有一些更好/更漂亮的方式做到這一點?

​​

回答

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 
+0

啊!尼斯想用索引代替對象。這幾乎就像我編輯的解決方案一樣,但是感覺問題比問題的「更好的」解決方案要比循環全部並檢查之後是否有匹配。 – gubbfett

+0

您可以將車主字段添加到指向人物對象的汽車,然後執行Listbox_Users.selecteditem = car.owner。但取決於你的代碼,你可能無法做到這一點 – Hamster

+0

這實際上是一個非常不錯的解決方案,閱讀起來更好。這是幾乎相同的問題,因爲我仍然需要循環列表框並檢查匹配的電子郵件以獲取該車的所有者,但將該車設置爲.Owner的人員仍然更漂亮。謝謝! :-) – gubbfett

相關問題