I have my code that is reading values from a database and then putting them into an array. I want to copy the values of this array to another array, however when I try, it keeps on throwing an exception,
Object reference not set to an instance of an object.
I don’t seem to see what is wrong. How can I fix this problem?
My code is here:
' Read values from a database and assign them to an array
Dim counter As Integer = 0
Dim reader As MySqlDataReader
reader = cmd.ExecuteReader()
Dim dataarray As string()
While reader.Read()
Dim datatoAdd As string = reader.GetValue(1) & ", " & _
reader.GetValue(2) & ", " & _
reader.GetValue(3) & ", " & _
reader.GetValue(6) & ", " & _
reader.GetValue(7) & ", " & _
reader.GetValue(8) & ", " & _
reader.GetValue(9) & ", " & _
reader.GetValue(10) & ", " & _
reader.GetValue(11)
dataarray(counter) = datatoAdd
End While
reader.Close()
connection.Close()
MessageBox.Show('Data added successfully)
Catch ex As Exception
MessageBox.Show(ex.Message)
Your statement
just declared dataarray — you defined that
dataarraycan point to an array of string. Currently, it does not point anywhere. You have to create a new array and assign it todataarray.The easiest way to do so is to specify the size of the array in the declaration:
This will create an array with indexes 0 to UPPER_BOUND (i.e., with UPPER_BOUND+1 elements). (If you don’t know the upper bound yet, don’t use an array, but use a
List(Of String)instead.)More details:
EDIT: You state in the comments that you don’t know the size of the array. In that case you shouldn’t be using an array at all. Arrays are by definition fixed-size data structures. (Yes, there’s
ReDim Preserve, but it’s still not a good idea.)Instead, use a resizable data structure such as
List(Of String). If you really need an array, you can convert it into an array afterwards.