Click here to Skip to main content
15,888,803 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello everyone,

Is there an easy way to get the values return in SQL using field names.
I have a function that executes a SELECT script.
VB
Public Function ExecuteQuery(ByVal SQL As String) As DataSet
    Dim dt As New DataSet
    Try
        If SQLConn.State = ConnectionState.Closed Then SQLConn.Open()
        Dim SQLCmd As New SqlCommand
        SQLCmd.Connection = SQLConn
        SQLCmd.CommandText = SQL
        SQLCmd.ExecuteReader()
        SQLCmd.Connection.Close()
        Dim SQLAdp As New SqlDataAdapter(SQLCmd)
        SQLAdp.Fill(dt)
    Catch ex As Exception
        dt = Nothing
    End Try
    Return dt
End Function

This is how I get the field values
VB
Dim dt As DataSet = ExecuteQuery(My.Resources.AddressFile.Replace("%%", trvSearch.SelectedNode.Tag))
MessageBox.Show(dt.Tables(0).Rows(0).Item(0))

Can I get data using field name:
VB
dt.items("Field01")

Is there a ResultSet in SqlClient?

Please help... Thanks
Posted
Updated 12-Jul-13 6:01am
v2
Comments
[no name] 12-Jul-13 12:20pm    
I am not sure exactly what it is that you are asking. I use an SqlDataReader to "get data using field name" which you are getting but throwing away without using.... SQLCmd.ExecuteReader()
mgoad99 12-Jul-13 12:42pm    
You would have to do something like dt.Tables(0).Rows(0).Item("Field01")

You are using a dataset which is made up of 1 or more tables. each table has 1 or more rows. Each row has 1 or more items. To get an item, you do have to specify the table, and row.

1 solution

Hi
Yes you can do it with DataReader object:

Public Function ExecuteQuery(ByVal SQL As String) As DataSet
      Dim dr As New SqlDataReader ' or OleDataReader
      Dim List<object> myReaderList = new List<object>()
      Try
          If SQLConn.State = ConnectionState.Open Then SQLConn.Close()
          Dim SQLCmd As New SqlCommand
          ConnectionState.Open
          SQLCmd.Connection = SQLConn
          SQLCmd.CommandText = SQL
          dr = SQLCmd.ExecuteReader()
          while(dr.Read())
             myReaderList.Add(dr.Read("FiealName"))
          end while
          SQLCmd.Connection.Close()
          ' you can remove SQLAdp and dt maybe you don`t need that ;)
          Dim SQLAdp As New SqlDataAdapter(SQLCmd)
          SQLAdp.Fill(dt)
      Catch ex As Exception
          dt = Nothing
      End Try
      Return dt
  End Function</object></object>


Of course you should note if you are close the connection you will lost reader so close connection after finished your work with reader.
Best Regards.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900