Skip to content

Instantly share code, notes, and snippets.

@NPS-ARCN-CAKN
Created January 5, 2017 15:35
Show Gist options
  • Save NPS-ARCN-CAKN/74baf42bab384426c7ebc4c9914a758e to your computer and use it in GitHub Desktop.
Save NPS-ARCN-CAKN/74baf42bab384426c7ebc4c9914a758e to your computer and use it in GitHub Desktop.
VB .Net: A function to return a DataTable from a database connection.
''' <summary>
''' Returns a DataTable from a database query defined by a ConnectionString.
''' </summary>
''' <param name="ConnectionString">ConnectionString to a database</param>
''' <param name="Sql">An SQL query</param>
''' <returns>DataTable</returns>
Private Function GetDataTable(ConnectionString As String, Sql As String) As DataTable
'the DataTable to return
Dim MyDataTable As New DataTable
'make a SqlConnection using the supplied ConnectionString
Dim MySqlConnection As New SqlConnection(ConnectionString)
Using MySqlConnection
'make a query using the supplied Sql
Dim MySqlCommand As SqlCommand = New SqlCommand(Sql, MySqlConnection)
'open the connection
MySqlConnection.Open()
'create a DataReader and execute the SqlCommand
Dim MyDataReader As SqlDataReader = MySqlCommand.ExecuteReader()
'load the reader into the datatable
MyDataTable.Load(MyDataReader)
'clean up
MyDataReader.Close()
End Using
'return the datatable
Return MyDataTable
End Function
@shafeekfsd
Copy link

Excellent....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment