不确定如何处理NullReferenceException

时间:2015-05-15 17:51:59

标签: mysql vb.net list nullreferenceexception

当我创建一组学生的表单加载时,我似乎没有理由收到NullReferenceException。这是处理表单加载的代码:

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

引用的mainStudentList是使用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

tempStudentList尝试加载mainStudentList中的值时,会发生特定异常。具体来说,它声明"对象引用未设置为对象的实例"。

1 个答案:

答案 0 :(得分:2)

确保首先初始化mainStudentList。

C#

$a2

VB.Net

$a3