0

How can I get MS-Access data in the array?

I tried this:

Dim i As Integer = 0
Dim farmers() As String = {}
sql = "SELECT * FROM users"
cmd = New OleDbCommand(sql, connection)
reader = cmd.ExecuteReader()
If Not reader.HasRows Then
    'nothing
ElseIf reader.HasRows Then
   Do While reader.Read
      farmers(i) = CStr(reader.Item(1))
      i += 1
   Loop
End If

For Each element As String In farmers
    MsgBox(element)
Next

It shows an error:

enter image description here

My MS-Access Database table is:

users

____________________________
|  ID |  Number    |  Name |
| 1   |  10        |  John |
| 2   |  15        |  Joe  |
| 3   |  7         | User3 |

and I want those 10 15 7 in array.

How can I get that? Or any other methods?

Any help is appreciated. Thank You

1 Answer 1

1

Your array has no dimension, you have to ReDim the array to contain all elements returned by the query Something like :

Dim i As Integer = 0
Dim farmers() As String = {}
sql = "SELECT * FROM users"
cmd = New OleDbCommand(sql, connection)
reader = cmd.ExecuteReader()
If Not reader.HasRows Then
    'nothing
ElseIf reader.HasRows Then
   '-->> Add this line 
   ReDim(farmers,reader.rows.count)

   Do While reader.Read
      farmers(i) = CStr(reader.Item(1))
      i += 1
   Loop
End If

For Each element As String In farmers
    MsgBox(element)
Next
Sign up to request clarification or add additional context in comments.

4 Comments

Error found in ReDim code. Can you help me by providing valid code? Please. Because I'm a beginner in VB.
Just press F1 on the ReDim word and you will get the help you need.
Error in reader.rows.count. It did not count rows. How can I count ?
Well, @PradipDhakal the above comment applies here too :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.