Advertisement
NAK

SqlDataReader simple (VB.NET)

NAK
Dec 10th, 2013
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
VB.NET 1.16 KB | None | 0 0
  1. ' put a dataGridView1 control on your form
  2. ' and don't forget to insert your SQL Connection string and SQL query into the code
  3.  
  4. Imports System.Data
  5. Imports System.Data.SqlClient
  6.  
  7. Public Class Form1
  8.  
  9.     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
  10.         ' Render data onto the screen
  11.         DataGridView1.DataSource = FillData("<Your SQL Connection String here>", "<Your SQL Query here>")
  12.     End Sub
  13.  
  14.     Private Function FillData(strConnection As String, SQLQuery As String) As DataTable
  15.         Dim dt As New DataTable
  16.         ' Open connection
  17.         Using conn As SqlConnection = New SqlConnection(strConnection)
  18.             conn.Open()
  19.             Dim cmd = New SqlCommand(SQLQuery, conn)
  20.             ' Create new DataAdapter
  21.             Using reader As SqlDataReader = cmd.ExecuteReader()
  22.                 ' Use DataAdapter to fill DataTable
  23.                 Try
  24.                     ' fill the DataTable
  25.                     dt.Load(reader)
  26.                 Catch ex As Exception
  27.                 End Try
  28.             End Using
  29.         End Using
  30.         ' return the DataTable
  31.         Return dt
  32.     End Function
  33. End Class
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement