cost
cost

Reputation: 4480

How do I get a string from an Access database?

I've been handed an Access database with 3 columns: Name, category, e-mail. What I'm trying to do is get out, as strings, all of the e-mails that match a given category.

I have a slight understanding SQL as I'm in the process of learning it. I've managed to churn out this bit of code, which populates a visual grid with the first names

Dim comm As New OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=.\AddressBook.mdb")
Dim addda As New OleDbDataAdapter("SELECT FirstName FROM Contacts", comm)
Dim dd As New DataTable("Name")
addda.Fill(dd)
DataGridView2.DataSource = dd

So I feel I'm getting fairly close, but I can't figure out how to get that list of first names to go into a string (or array of strings). All of the online tutorials and books I find seem to go over just displaying the data in a dataview.

Point in the right direction?

Upvotes: 1

Views: 2439

Answers (2)

Chris Tifer
Chris Tifer

Reputation: 1

I'm sure LarsTech's response will work, but going back to your original example, you can always loop through your DataTable (dd), looking at the DataRow collection.

Dim Names As New List(Of String)
For Each R As DataRow In dd.Rows.Count
    Names.Add(R.Item("FirstName").ToString)
Next

Then you can just check the count of Names and if it's greater than 0, iterate over that collection.

Upvotes: 0

LarsTech
LarsTech

Reputation: 81610

try this:

Dim Names As New List(Of String)

Using comm As New OleDbConnection("Provider...")
  comm.Open()
  Using cmd As New OleDbCommand("SELECT FirstName FROM Contacts", comm)
    Using reader As OleDbDataReader = cmd.ExecuteReader
      While reader.Read
        Names.Add(reader("FirstName").ToString)
      End While
    End Using
  End Using
End Using

The Using format will automatically dispose of your data objects.

Upvotes: 1

Related Questions