Why is my listbox throwing a NullReferenceException?

48 views Asked by At

As a project, I've been making the visual part of a library database. One of the screens required is a display of all things pulled from a SQL request. This much seems to work. However, I'm getting caught up on an odd issue: the ListBox that I'm trying to populate with data from the database doesn't seem to be getting recognized.

Here's my code:

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) 'error here
        Next
    End Sub
End Class

and here's the exception:

exception

The reason I know it's not a bad variable or something is because the value that gets assigned to coll(index).ISBN is correct and from the database:

proof

The error occurs on Display_Load, so I haven't even been able to check if SelectedIndexChanged has the same bug, although I would assume it does.

This leads me to believe that the issue is with the ListBox. To check if it was just corrupted, I made a separate version of Display.vb and changed the rest of the code in the project to run with that, but it still ran the same error. There's no weird properties on theBox that I can find, the only real weird thing is that it sends as Nothing.

I've searched on Google for like 3 hours with the various errors and messages I can make it show by doing different things to it, but nobody seems to be having this particular problem. If there's a problem with my code, what is it? Alternatively, if there's something wrong with the autogenerated ListBox, how can I fix that? Thanks!

1

There are 1 answers

1
9box On

Figured out the issue, if anyone finds this at a later time

As it turns out, putting InitializeComponent() in the Public Sub New() is NOT optional, and that is in fact what initializes all the code.

I had made this error at the very start of making the class, so I didn't catch it until I found it in some unrelated question.

For future reference, the format for Public Sub New is

Public Sub New()
   InitializeComponent()
   (code here)
End Sub