Error loading small Access table into an array.

Ok, here is the code, very simple:

Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim strConn As String = "DSN=BattleTide;UID=;Password=;"
Dim myConn As New Odbc.OdbcConnection(strConn)
Dim myadapter As New OdbcDataAdapter
Dim mydataset As New DataSet
Dim myquery As String = "SELECT * FROM base_unit_data"
Dim mycommand As New OdbcCommand(myquery, myConn)
Dim myreader As OdbcDataReader
Dim p1Array(300) As Unit
Dim counter, i As Integer

myConn.Open()
'myadapter.SelectCommand = New Odbc.OdbcCommand(myselect, myConn)
'myadapter.Fill(mydataset)
myreader = mycommand.ExecuteReader

If myreader.HasRows Then
counter = 0
While myreader.Read()
MsgBox(myreader.GetString(1))
p1Array(counter).Unit_Name = myreader.GetString(1)
counter = counter + 1
End While
End If
End Sub

When it reaches the line "p1Array(counter).Unit_Name = myreader.GetString(1), I receive the error:

NULL Reference Exception was unhandled: Object reference not set to an instance of an object.

The line right before it - "MsgBox(myreader.GetString(1))", returns a proper string, so why would I be getting a null reference error?

John

[1317 byte] By [JohnWilliams] at [2007-12-22]
# 1

You declared p1Array as an array of 300 UNIT objects, but none of the objects have been instantiated (i.e by using the New Keyword). So it's not the reader, but the UNIT that is a NULL reference

I haven't done VB in while, but try this:

p1Array(counter) = new Unit()

p1Array(counter).Unit_Name = myreader.GetString(1)

A second thing: unless you are always sure there will be 300 records in the datatable, you might want to initialize your array so it contains only as much elements as there are datarows... (or use an arraylist... you can dynamically add items to that)

SvenDeBont at 2007-8-30 > top of Msdn Tech,Visual Basic,Visual Basic Language...