How do I copy values of one array to another in VB.NET?
I have m开发者_开发知识库y 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
Dim dataarray As string()
just declared dataarray -- you defined that dataarray
can point to an array of string. Currently, it does not point anywhere. You have to create a new array and assign it to dataarray
.
The easiest way to do so is to specify the size of the array in the declaration:
Dim dataarray(UPPER_BOUND) As String
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:
- MSDN: Arrays in Visual Basic
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.
VB arrays start at 0 and not 1 don't they? Could that be the problem?
See - http://patorjk.com/programming/tutorials/vbarrays.htm
精彩评论