我有一个正常工作的列表框,除了我点击列表框中的不 -item之外,我发现错误时,一切似乎都顺利进行:
"对象引用未设置为对象的实例。"
当我点击列表框中的空白区域时,为什么会收到此消息?如果我在点击实际项目时遇到错误,我会更好理解,但现在当我点击非 -item时,我收到此错误。
以下是我在MainForm上显示错误的地方:
Private Sub UpdateContactInformationFromRegistry()
Dim contact As Contact = m_contacts.GetContact(listResults.SelectedIndex)
cmbCountries.SelectedItem = DirectCast(contact.AddressData.Country, Integer)
txtFirstName.Text = contact.FirstName
txtLastName.Text = contact.LastName
txtStreet.Text = contact.AddressData.Street
txtZip.Text = contact.AddressData.ZipCode
txtCity.Text = contact.AddressData.City
End Sub
m_contact.GetContact方法:
Public Function GetContact(index As Integer) As Contact
If index < 0 OrElse index >= m_contactRegistry.Count Then
Return Nothing
End If
Return m_contactRegistry(index)
End Function
m_contactRegistry是一个列表
Public Class ContactManager
Private m_contactRegistry As List(Of Contact)
Public Sub New()
m_contactRegistry = New List(Of Contact)()
End Sub
更新V2 列表框事件
SelectedIndexChanged处理程序:
Private Sub listResults_SelectedIndexChanged(sender As Object, e As EventArgs) Handles listResults.SelectedIndexChanged
UpdateContactInformationFromRegistry()
End Sub
答案 0 :(得分:0)
如果未选择任何项目,则返回负值1(-1)。
所以你也可以这样做:
Private Sub listResults_SelectedIndexChanged(sender As Object, e As EventArgs) Handles listResults.SelectedIndexChanged
If listResults.SelectedIndex <> -1 Then
UpdateContactInformationFromRegistry()
End If
End Sub