5/5/11

How to Access a VB Query

Knowing how to execute queries and access the information returned by a query using Microsoft Visual Basic.NET can save you time if you're working with databases. Microsoft Office Access is a relational database management system offered in the Office suite, while a query is used to retrieve information from a database table. VB.NET is a computer programming language that is relatively easy to learn and use. Fortunately, you can write VB code and access a VB query in just a few minutes.
    • 1

      Open Microsoft Visual Basic Express. Click "New Project...," and then select "Windows Forms Application." Click "OK."

    • 2

      Double-click "Button" on the "Toolbox" pane to add a new button control. Double-click "DataGridView" to add a new grid control. Double-click "Button1" to open the "Form1.vb"module. Press "Ctrl" and "A" simultaneously followed by "Delete" to remove all existing code.

    • 3

      Copy and paste the code below to connect to the Northwind database, query the "Products" table and display the contents through the "Data Grid View" control:

      Imports System.Data.Odbc.OdbcConnection

      Public Class Form1

      Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

      Dim nwindConn As Odbc.OdbcConnection

      Dim qryStr As String

      nwindConn = New Odbc.OdbcConnection("DSN=NORTHWIND")

      nwindConn.Open()

      qryStr = "SELECT Products.[Product Code], Products.[Product Name], "

      qryStr = qryStr & "Products.Description, Products.[Standard Cost], "

      qryStr = qryStr & "Products.[List Price], Products.[Reorder Level] "

      qryStr = qryStr & "FROM Products;"

      Dim da As New Odbc.OdbcDataAdapter(qryStr, nwindConn)

      Dim ds As New Data.DataSet

      da.Fill(ds, "myTable")

      With DataGridView1

      .DataSource = ds.Tables("myTable")

      End With

      nwindConn.Close()

      nwindConn.Dispose()

      nwindConn = Nothing

      End Sub

      End Class

    • 4

      Edit the following line of code by removing "NORTHWIND" and typing the name of your DSN (DSN= <your DSN Name>):

      nwindConn = New Odbc.OdbcConnection("DSN=NORTHWIND")

      Press "F5" to run the program and click "Button1."

  • No comments: