MS Access: I can pull data, but can't pull field name?

NJDubois

Well-known member
Joined
May 15, 2008
Messages
84
Programming Experience
Beginner
I am trying to work with an access database.

If this line pulls data from a dataset and puts it into a textbox:
TextBox1.Text = Me.A_DataSet.a_Table.Rows(0).Item(0).ToString

How would I pull the field name? For Example, in this database I have 3 fields:

ID, Name, Phone
1, NJD, 123
2, DRD, 322

So pulling row 0 item 0 would give me "1"
But how do I get "ID", "Name", or "Phone"?

its gotta be
Me.A_Dataset.a_Table.?????

Any help would be much appreciated! And thanks in advance!
Nick
 
Use the ColumnName property

VB.NET:
Dim dtTest As New DataTable

'Adds 10 generic columns to the table
For intIndex As Integer = 0 To 9
    Dim colNew As New DataColumn
    dtTest.Columns.Add(colNew)
Next


'Display column index & name
For Each col As DataColumn In dtTest.Columns
    Console.WriteLine("Column Index: {0:00}{1}Column Name: {2}" 
                             , col.Ordinal _
                             , ControlChars.Tab _
                             , col.ColumnName)
Next

Console.Read()
 
I usually use the column names in each row by name rather than by index:
VB.NET:
TextBox1.Text = Convert.ToString(A_DataSet.a_Table.Rows(0)("Name"))
TextBox2.Text = Convert.ToString(A_DataSet.a_Table.Rows(0)("Phone"))
This way if the query get's changed later and the columns are somehow in a different order, I'm getting them by name, not index so I don't have to reorder it all in my code too.
 
Using the column indexes is supposed to be faster & more efficient. But I agree with JB; calling the columns by there name not only makes code easier to read but prevents conflicts later on when you reorder/add columns.

With that said; I was under the impression that the origianal poster didnt know what the column names were... although if he's loading the data in the first place he should.
 
Awesome! Much thanks!

Field_Name = DataSet.A_Table.Columns(cur_Field).ColumnName

Works great! Many thanks!

It took some research, but I can work with rows. Creating, and "adding" rows and that's where my next question is. How do I get data persistence? When I rebuild my project the data that I added, and cycled through and could view as if it was a new record isn't there anymore.

Dataset.a_Table.Rows.Add(new_row)
TableAdapter.Update(DataSet.a_Table)

adds the new row/record to the active database, but that gets cleared on rebuild.

I'm lost!!

thanks again for the help.
Nick
 
Back
Top