• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 183
  • Last Modified:

How do get the column names for a query?

How do get the column names for a query?  I normally do something like this to get the data.

        Connection = New SqlConnection(the_ConnectionString)
        Command = New SqlCommand(Report_SQL, Connection)
        Connection.Open()
        Reader = Command.ExecuteReader()

        Do While Reader.Read()
        Loop()
0
HLRosenberger
Asked:
HLRosenberger
1 Solution
 
wdosanjosCommented:
Check the SqlDataReader.GetSchemaTable Method:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.getschematable.aspx

Something like this:
' Displays all columns in 'Reader'
For Each row In Reader.GetSchemaTable().Rows
     Console.WriteLine(row("ColumnName"))
Next

Open in new window

0
 
David11011Commented:
I'm not sure what you are trying to do but here is some code that may help you.
This will get the number of columns in your query table and then loop through the returned values and find all the column names.

 
        Dim CON As New SqlConnection("connectionStringHere")
        Dim myQuery As String = "select * from SQLtable"
        Dim myCommand As SqlCommand = New SqlCommand(myQuery , CON)
        Dim myAdapter As SqlDataAdapter = New SqlDataAdapter(myCommand)
        Dim myDataSet As Data.DataSet = New Data.DataSet
        myAdapter.Fill(myDataSet, "testTable")

        Dim numberOfColumns As Integer = myDataSet.Tables("testTable").Columns.Count
        Dim i As Integer = 0
        Dim ColumnName As String
        Dim myColumnsString As String = Nothing
        Dim myColumnsArray(0, 50) As String

        For i = 0 To numberOfColumns - 1 Step i + 1

            'Get name of the column number that is equal to i
            ColumnName = myDataSet.Tables("testTable").Columns(i).ToString

            'save the column name to a comma delimited string
            myColumnsString = myColumnsString + ", " + myColumnName

            'save the column to an array
            myColumnsArray(0, i) = myColumnName
        Next

Open in new window

0
 
HLRosenbergerAuthor Commented:
Thanks!
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now