1

I have two Class and I want to save my data into arrays form text box like this:
Students.Name(txtID.Text-1).MathMark = txtMark.Text
but I get error: Object reference not set to an instance of an object

my code is:

Dim StudentsNumber as Integer = txtstdnum.Text
Dim Students as New StudentsInf(StudentsNumber)

Students.Name(txtID.Text-1).MathMark = txtMark.Text


Public Class StudentsInf

    Private mName() As String

    Sub New(ByVal StudentNumbers As Integer)
        ReDim mName(StudentNumbers-1)
    End Sub

    Public Property Name(ByVal Index As Integer) As LessonsMark
        Get
            Return mName(Index)
        End Get
        Set(ByVal Value As LessonsMark)
            mName(Index) = Value
        End Set
    End Property

End Class

Public Class LessonsMark

    Private mMathMark() As Object

    Public Property MathMark() As Object
        Get
            Return mMathMark
        End Get
        Set(ByVal Value As Object)
            mMathMark = Value
        End Set
    End Property

End Class
farzad89
  • 19
  • 6

1 Answers1

1

This:

Private mName() As String

needs to be:

Private mName() As LessonsMark

then you have to create the objects in your constructor, something like:

Sub New(ByVal StudentNumbers As Integer)
  ReDim mName(StudentNumbers - 1)
  For i As Integer = 0 To StudentNumbers - 1
    mName(i) = New LessonsMark()
  Next
End Sub

then it looks like your LessonsMark class is declaring an array of objects when it looks like it should be just a string property:

Public Class LessonsMark
  Private mMathMark As String

  Public Property MathMark As String
    Get
      Return mMathMark
    End Get
    Set(ByVal Value As String)
      mMathMark = Value
    End Set
  End Property
End Class
LarsTech
  • 80,625
  • 14
  • 153
  • 225
  • When I use 'Dim Students as New StudentsInf(StudentsNumber)' in another module to read my datas again ... I can't. I lose my datas. what can I do ? – farzad89 Oct 16 '14 at 22:33
  • @farzad89 useing *new* creates a new instance, so you would have to reference the existing variable. – LarsTech Oct 16 '14 at 22:39
  • Exactly I want to write and read my datas for each student as a array, and yes when I useing _new_ it creates a new instance. What can I do ? – farzad89 Oct 16 '14 at 22:50
  • @farzad89 You would have to pass the Students array to whatever class or function you are calling. – LarsTech Oct 16 '14 at 23:00
  • That's not possible for me to pass the students array to a Class in every module. I need **Students.Name(ID).MathMark** as a public data ? – farzad89 Oct 16 '14 at 23:17
  • @farzad89 Then make it public shared, but that's a code smell. Global variables lead to tough to debug errors and is widely considered a bad programming practice. – LarsTech Oct 16 '14 at 23:20