You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何我的ListBox抛出NullReferenceException异常?求排查方案

图书馆数据库可视化界面ListBox控件空引用问题

我正在开发图书馆数据库的可视化界面项目,SQL查询返回数据的功能正常,但遇到一个奇怪的问题:用于填充数据库数据的ListBox控件theBox无法被识别,运行时该控件的值为Nothing,导致空引用异常。

代码示例

Public Class Display
    Dim coll As New Collection
    Private Sub exiter_Click(sender As Object, e As EventArgs) Handles exiter.Click
        Me.Close()
    End Sub

    Public Sub New(ByVal Collection As Collection)
        coll = Collection
    End Sub
    Private Sub theBox_SelectedIndexChanged(sender As Object, e As EventArgs)
        Dim book As Book
        Dim correctBook As Book
        For Each book In coll
            If book.ISBN = theBox.SelectedValue Then
                correctBook = book
            End If
        Next
        Title.Text = book.BookTitle
        Author.Text = book.Author
        ISBN.Text = book.ISBN
        Copyright.Text = book.Copyright
        Copies.Text = book.Copies
    End Sub

    Private Sub Display_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        For index As Integer = 1 To coll.Count
            theBox.Items.Add(coll(index).ISBN) ' 此处抛出空引用异常
        Next
    End Sub
End Class

问题细节

  • 异常发生在Display_Load方法中,尝试向theBox.Items添加元素时触发
  • 已确认coll(index).ISBN的值正确,确实来自数据库查询结果
  • 尚未验证theBox_SelectedIndexChanged事件是否存在相同问题

已做排查

  • 新建了Display.vb文件并调整项目代码,问题依旧
  • 检查theBox控件的属性,未发现异常设置
  • 搜索相关问题3小时,未找到完全匹配的案例

请问这是代码逻辑问题,还是自动生成的ListBox控件本身的问题?该如何解决?


内容的提问来源于stack exchange,提问作者9box

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 02:17:11