Minggu, 06 Mei 2012

Database Coding OLEDB DataAdapter di VB.NET


Untuk membuat program database menggunakan teknologi OLEDB dengan DataAdapter seperti yang dipakai pada Wizard tetapi menggunakan kode program, yang berbeda hanya koneksi awalnya saja yaitu di event onLoad. Barikut ini kode programnya :

Imports System.Data.OleDb
Imports System.IO

Public Class FAccessOLEDBDataAdapter
    Public cn As OleDbConnection
    Public da As OleDbDataAdapter
    Public ds As DataSet
    Public WithEvents bs As BindingSource

    Private Sub FAccessOLEDBDataAdapter_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Path.GetDirectoryName(Application.ExecutablePath) & "\world.mdb")

        da = New OleDbDataAdapter
        ds = New DataSet

        da.SelectCommand = cn.CreateCommand
        da.SelectCommand.CommandType = CommandType.Text
        da.SelectCommand.CommandText = "SELECT name, address, phone FROM contacts"
        da.Fill(ds, "contacts")

        bs = New BindingSource
        bs.DataSource = ds
        bs.DataMember = "contacts"

        gContacts.DataSource = bs
    End Sub

    Private Sub bRefresh_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bRefresh.Click
        gContacts.DataSource = Nothing
        bs.DataSource = Nothing

        ds.Clear()
        da.SelectCommand.CommandType = CommandType.Text
        da.SelectCommand.CommandText = "SELECT name, address, phone FROM contacts WHERE name LIKE '%" & tFind.Text.Trim & "%'"
        da.Fill(ds, "contacts")

        bs = New BindingSource
        bs.DataSource = ds
        bs.DataMember = "contacts"

        gContacts.DataSource = bs
    End Sub