How to display MS Access table on DataGridView VB.Net

Continuing my previous tutorial, here I want to show you how to display or populate MS Access table into a DataGridView under Visual Basic .NET. Its pretty easy to load and display MS Access table on our program/form.

Design the form

form 1

As you can see, I have two button Connect and Show Data. The Connect button is used to connect to the database and the other one is to display a table content to DataGridView.

The Code

First we need to create a module. This module will handle every connections to the database through OleDb connection. To add a module, go to Project | Add New Item. Select Module from the list and enter the name of the new module.

add module to vb.net 2015

The following code are typed inside a module called MyModuleConnect

Imports System.Data.OleDb
Module MyModuleConnect
    Public MyConn As OleDbConnection
    Public Constring As String
    Public Provider, Location As String
    Sub Connect()
        Provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
        Location = "E:\Personal\09. Blog\Tutorial_01.accdb"
        Constring = Provider & Location
        MyConn = New OleDb.OleDbConnection(Constring)
        MyConn.Open()
    End Sub
End Module

Now back to the main form and we will add code for the Connect button. Connect button will attempt to open the connection to the database.

Private Sub btnConnect_Click(sender As Object, e As EventArgs) Handles btnConnect.Click
        Try
            MyModuleConnect.Connect()
            MsgBox("Connection Status :" & MyModuleConnect.MyConn.State.ToString, MsgBoxStyle.Information)
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

vb.net tutorial 01

Now, Show Data button code:

Private Sub btnShowData_Click(sender As Object, e As EventArgs) Handles btnShowData.Click
        Dim strSQL As String
        Dim MyAdapter As OleDb.OleDbDataAdapter
        Dim Ds As New DataSet
        Try
            strSQL = "Select * from Tbl_DHCollar"
            MyAdapter = New OleDb.OleDbDataAdapter(strSQL, MyModuleConnect.MyConn)
            MyAdapter.Fill(Ds, strSQL)
            Me.DataGridView1.DataSource = Ds
            Me.DataGridView1.DataMember = strSQL
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try

    End Sub

Run the program

vb.net tutorial 02

Thank you. Hope this is useful for anyone who wants to start learning Visual Basic 2015.

Admin

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.