为何我的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
相关产品推荐
相关产品推荐

