Click here to Skip to main content
15,881,600 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,

I want to add value to two-dimensional array. But I get an error "Object reference not set to an instance of an object."

I wanto to do like that;

LinkedUnits(0,1) = True
LinkedUnits(0,2) = 3

LinkedUnits(1,1) = False
LinkedUnits(1,2) = 1

How can I resolve this error?

This is my code block:

VB
Dim LinkedUnits(,) As String

For t As Integer = 0 To dgUnits.Rows.Count - 1

  If dgUnits.Rows(t).Cells(0).Value = False Then

     dgUnits.Rows(t).Cells(0).Value = True

     LinkedUnits(t, 0) = dgUnits.Rows(t).Cells(0).Value.ToString()'I get error in this line
     LinkedUnits(t, 1) = dgUnits.Rows(t).Cells(2).Value.ToString()

     Dim item As String
     item = String.Format("{0} - {1}", dgUnits.Rows(t).Cells(2).Value.ToString(), dgUnits.Rows(t).Cells(3).Value.ToString()

     lstUnits.Items.Add(item)
     lstUnits.Sorted = True

  End If

Next


Thanks
Posted

Quote:
Dim LinkedUnits(,) As String

This just create a (null) reference. You have to Create it the actual bidimensional array, see, for instance "How to: Initialize a Multidimensional Array"[^]. That assuming you know in advance array dimensions. On the other hand, if you don't know in advance the array dimensions) then the array doesn't fit your needs and you have to use another collection (like, for instance a List).
 
Share this answer
 
You have created a variable to hold your array of data:
VB
Dim LinkedUnits(,) As String
But you haven't allocated any data to it!

It's like taking a paper bag and passing it round to your friends - if you haven't put any sweets in the bag to start with, they are going to wonder what you are doing because they try to get a sweet and the bag is empty!

Try something like this:
VB
Dim LinkedUnits(,) As String = 
New String(dgUnits.Rows.Count, 2)
 
Share this answer
 
Comments
bellatriks 22-Aug-15 6:18am    
Hi,

Thanks for your answer. I use your code but I have an error like "'Integer values cannot be converted to 'Char'."

Thanks
OriginalGriff 22-Aug-15 6:24am    
You need to think about this - I don't know exactly what you are trying to do, but it looks rather odd.
You declared the array as strings - and all the code you show that uses it puts strings in. So where are you using integers?

Remember, we can't see your screen, access your HDD, or read your mind!
bellatriks 22-Aug-15 6:25am    
Hi,

I solved that error. I tried "Dim LinkedUnits(dgUnits.Rows.Count, 2) As String"
It's work :)

Thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900