Hello how to access class variables within an array

Peter Smedley 21 Reputation points
2021-12-31T13:53:08.403+00:00

I am trying to create a database of events system in VB.net
whenever i try to access a variable within the array using
Events(x).EventName it creates a "
Dim Events(63) As EventRecord 'global as to be accessed by any subroutine
Dim Event1 As EventRecord

Public Class EventRecord
Public EventDate, EventTimeTaken As Integer 'creates structure for records of each event
Public EventMembers(63), EventNotes, EventName As String 'multiple data types are stored, meaning it must be a record
Public EventMoneyMade, EventCost, EventHourlyProfit, EventProfit As Decimal 'global as to be accessed by any subroutine
End Class

++ Event1 is then populated and added to the array in PopulateArray()

Sub PopulateArray()
    Dim Empty As Boolean = False
    Dim Temp
    Dim j As Integer = 0
    While Empty = False
        Temp = Events(j)
        If Temp = Nothing Then
            Empty = True
            Events(j) = Event1
            Console.WriteLine("Array populated at location {0}", j)
            Console.WriteLine(Events(j).EventName) #but this line creates an error
        Else j = j + 1
        End If
    End While
End Sub

The error is "Object reference not set to an instance of an object"

Any help is greatly appreciated

Developer technologies Visual Basic for Applications
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.5K Reputation points
    2021-12-31T21:12:23.077+00:00

    Probably Event1 was not initialised. Execute something like 'Event1 = New EventRecord' before calling PopulateArray. Also assign a name to Event1.EventName.

    By the way, instead of arrays you can use a 'Dim Events as New List(Of EventRecord)' and append an event using Events.Add. The list's size will be adjusted automatically.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.