matt_t
matt_t

Reputation: 89

Altering array values in VB.NET

I'm using a 2D array to store data in a grid and all the data is ones and zeros. By default, the array is all zeros. When I attempt to modify values in the array using variable(y)(x) = 1 where x and y are integers in range it changes the value to 1 in the entire column, not just a single cell.

For example:

Public cells(19)() As Integer

'Code to  populate it with zeros goes here

Public Sub modifyCells(ByVal x As Integer, ByVal y As Integer)
    cells(x)(y) = 1
End Sub

Whenever I call modifyCells(0,0) I get the value of every sub-array looking like this:

1,0,0,0,0,0,0,0,0,0

Whereas I want this to happen only to the first sub array (i.e the value at cells(0)(0) = 1 and only that value).

How can I manage this? Thanks in advance.

(If it makes any difference the code used to populate the array is below)

Public Sub clear()
    Dim A1() As Integer = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
    For y = 0 To 19
        cells(y) = A1
    Next
End Sub

Upvotes: 0

Views: 755

Answers (2)

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120937

You are basically adding a reference to the same array to each position in cells.

Try this instead:

Public Sub clear()
    For y = 0 To 19         
        cells(y) = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}     
    Next 
End Sub 

Upvotes: 0

Gabe
Gabe

Reputation: 86718

Your problem is that you are populating each row with exactly the same array. You need to move your local variable definition into the loop:

Public Sub clear()
    For y = 0 To 19
        Dim A1() As Integer = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
        cells(y) = A1
    Next
End Sub

Upvotes: 1

Related Questions