1

When my form for creating a group of students loads up, I receive a NullReferenceException for seemingly no reason. This is the code that handles the form loading:

Private Sub AddGroupForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    For i As Integer = 0 To Form1.lstStudents.Items.Count - 1
        lstStudentList.Items.Add(Form1.lstStudents.Items.Item(i))
    Next
    tempStudentList.AddRange(Form1.mainStudentList)
    btnAllOut.Enabled = False
    btnOneOut.Enabled = False
End Sub

The mainStudentList referred to is a list that is populated upon loading by using MySQL:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Try
        Dim conn As New MySqlConnection("server=localhost;user=root;database=new_project;port=3306;password=********;")
        conn.Open()
        Dim command As New MySqlCommand("SELECT * FROM students WHERE deleted=0 ORDER BY lastName;", conn)
        Dim dataSet As New DataSet()
        Dim dataAdapter As New MySqlDataAdapter()
        dataAdapter.SelectCommand = command
        dataAdapter.Fill(dataSet, "students")
        Dim dataTable As DataTable = dataSet.Tables("students")
        For Each row As DataRow In dataTable.Rows
            Dim newStudent As New Student
            newStudent.intIDNum = row.Item("passCode")
            newStudent.strFirstName = row.Item("firstName")
            newStudent.strLastName = row.Item("lastName")
            newStudent.chrGender = row.Item("gender")
            newStudent.dateDOB = row.Item("dateOfBirth")
            newStudent.intAge = CInt(Today.Year - newStudent.dateDOB.Year)
            newStudent.intYearGroup = row.Item("yearGroup")
            newStudent.intSkillLevel = SByte.Parse(row.Item("skillLevel"))
            mainStudentList.Add(newStudent)
            lstStudents.Items.Add(newStudent.nameConcat(newStudent.strFirstName, newStudent.strLastName))
        Next
        conn.Close()
    Catch ex As Exception
        MsgBox("Error: " & ex.ToString())
    End Try
End Sub

The specific exception occurs when the tempStudentList attempts to load the values in the mainStudentList. Specifically, it states that "Object reference not set to instance of an Object".

  • 1
    Is it possible that the student DOB filed could be null or empty for a student? If so, you would want to use `ISNULL` to check and adjust the value. – alybaba726 May 15 '15 at 17:55
  • possible duplicate of [What is a NullReferenceException and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Ňɏssa Pøngjǣrdenlarp May 15 '15 at 18:57

1 Answers1

2

Make sure mainStudentList has been initialized first.

c#

List<Student> mainStudentList = new List<Student>();

VB.Net

Dim mainStudentList As New List(Of Student)()
Mad Dog Tannen
  • 6,725
  • 4
  • 28
  • 53
Barry Colebank Jr
  • 1,831
  • 2
  • 15
  • 16