0

I'm making a program which you can input a student name and 3 exam scores and then have it added to an array of students which is printed on a list. But I get this error on the 'Exam1(Index) = Mark1' line of code and i don't know how to fix it: System.NullReferenceException: 'Object reference not set to an instance of an object.'

Public Class Form1
    Dim StudentName(), Identity() As String
    Dim Exam1(), Exam2(), Exam3() As Integer
    Dim Index As Integer = 0

    Private Sub btnDetails_Click(sender As Object, e As EventArgs) Handles btnDetails.Click
        For Index = 0 To Index
            lstStudent.Items.Add(Identity(Index))
        Next Index
    End Sub

    Dim Average As Decimal
    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        Dim Mark1, Mark2, Mark3 As Integer

        Mark1 = CInt(txtMark1.Text)
        Mark2 = CInt(txtMark2.Text)
        Mark3 = CInt(txtMark3.Text)

        StudentName(Index) = txtStudentName.Text
        Exam1(Index) = Mark1
        Exam2(Index) = Mark2
        Exam3(Index) = Mark3
        Index = Index + 1

        Identity(Index) = StudentName(Index) & Exam1(Index) & Exam2(Index) * Exam3(Index)
    End Sub
End Class
AmalJo
  • 106
  • 9
  • Nice homework. You should read something about using arrays. Maybe this will help you https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/arrays/ or https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/arrays/how-to-initialize-an-array-variable – muffi Jan 08 '18 at 13:24
  • Your arrays are declared but never initialized (a colored underline should be visible). If you can't set a dimension, you have to `Redim Preserve` the array (bad) each time you need to add an item to it, preserving its values. + Your MarkN integers are pretty much useless; make them usefull: `If Integer.TryParse(txtMarkN.Text, MarkN) = True Then ...`. CInt(ing) a string input is deadly. + `Identity(Index)` will be a mess. + I suggest to set Option Strict and Option Explicit to true (or ON in your Project properties or VS Options -> Projects and Solutions -> VB Defaults). – Jimi Jan 08 '18 at 14:54
  • Unless you have a constraint that arrays must be used, you'd be better off using Lists. Also, the [answer](https://stackoverflow.com/a/4660186/832052) to the duplicate covers your case specifically in the **Array** section. – djv Jan 08 '18 at 15:52
  • 1
    as @djv said, you should definitely use lists, but I would also add that you should create a `Student` class with the properties .. `Name`,`Identity`,`Exam1`,`Exam2`,`Exam3`, and then create a `List (Of Student)`. In the long run, your code will be much more readable and maintainable – David Wilson Jan 08 '18 at 22:39

0 Answers0