0

I'm trying to assign an arrayList a instance of a class but it is giving me the following error.

Object reference not set to an instance of an object.

This is my code that assigns it.

Public memberList As ArrayList

Public Sub LoadUser()
Dim userId As Integer = 0
    Dim userData As Data.DataTable = oExecuteSimpleQuery_DT("QA", "SELECT * FROM Member")
    If userData IsNot Nothing Then
        For Each user As Data.DataRow In userData.Rows
            If memberList(userId) Is Nothing Then
                memberList(userId) = 1
            End If
            memberList(userId) = New clsMember(user("UserID"), user("Firstname"), user("Secondname"), user("Username"), user("Password"), user("Email"), user("Rights"))
            userId += 1
        Next
    End If
End Sub
Victor Zakharov
  • 25,801
  • 18
  • 85
  • 151
James
  • 31
  • 7

2 Answers2

3

In the code shown in your question you do declare the memberList variable, but you do not create an instance. In order to solve the error, change the first line to:

Public memberList As New ArrayList()

Two side nodes:

  • Instead of using ArrayList, have a look at List(Of T). It offers almost the same functionality, but is strongly typed.
  • A NullReferenceException is a common error that is worth understanding. See this link for details on the reasons and on how to fix them.
Community
  • 1
  • 1
Markus
  • 20,838
  • 4
  • 31
  • 55
1

try this:

Public memberList as New List(Of clsMember)


Public Sub LoadUser()
 Dim userId As Integer = 1
 Dim userData As Data.DataTable = oExecuteSimpleQuery_DT("QA", "SELECT * FROM Member")
 If userData IsNot Nothing Then
    For Each user As Data.DataRow In userData.Rows
        memberList.Add(New clsMember(user("UserID"), user("Firstname"), user("Secondname"), user("Username"), user("Password"), user("Email"), user("Rights"))
        userId += 1
    Next
 End If
End Sub
Ranhot
  • 344
  • 2
  • 14
  • Thanks seems to have worked although now another error is appearing 'Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index' – James Apr 25 '14 at 12:12
  • Your index out of range is being caused by the data rows that uou are looping through. If its a grid (and I suspect it is) then the rows are numbered from 0 not 1 (you need to take account of the header row). So loop through the grid (ie for index as integer = 0 to [do you processing here] next. That should solve that problem – Dom Sinclair Apr 25 '14 at 12:42