I want to assign 2D array to DataGridView.
There are 2 buttons, the first is an array button which will add my inputs to the array every time I press it.
The second button is a submit button that will assign all of the values of the array to the DataGridView.
But I just can't work it out, every time I press the array button, the value is replaced by the new value I inputted.
Here's the code:
Public Class Form2
Dim array(1, 4) As String
Private Sub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
For i = 0 To array.GetUpperBound(0)
DataGridView1.Rows.Add(array(i, 0), array(i, 1), array(i, 2), array(i, 3))
Next
End Sub
Private Sub btnArray_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnArray.Click
ReDim array(1, 2)
Dim id, name As String
id = txtID.Text
name = txtName.Text
For i = 0 To array.GetUpperBound(0)
array(i, 0) = id
array(i, 1) = name
Next
End Sub
End Class
ReDim array(1, 2)all that is doing is just changing it from a 1 by 4 dimension to a 1 by 2 dimension. The next problem is that you are just overwriting with the for loop not adding a new dimension to the array. Here is what you need to do. changeReDim array(1, 2)toReDim array(array.GetUpperBound(0) + 2, 4)take out the for loop and just put ` array(array.GetUpperBound(0) , 0) = id` andarray(array.GetUpperBound(0) , 1) = namehere is the redim referencePreserveon theredimso it should beReDim Preserve array(array.GetUpperBound(0) + 2, 4)notReDim array(array.GetUpperBound(0) + 2, 4)