Jumat, 27 April 2012

Database Coding OLEDB DataAdapter di C#.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 :

using System.Data.OleDb;
using System.IO;

namespace AllDB
{
    public partial class FAccessOLEDBDataAdapter : Form
    {
        public OleDbConnection cn;
        public OleDbDataAdapter da;
        public DataSet ds;
        public DataTable tb;

        public FAccessOLEDBDataAdapter()
        {
            InitializeComponent();
        }

        private void FAccessOLEDBDataAdapter_Load(object sender, EventArgs e)
        {
            OleDbConnection 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.DataSource = ds;
            bs.DataMember = "contacts";

            gContacts.DataSource = bs;
        }

        private void bRefresh_Click(object sender, EventArgs e)
        {
            gContacts.DataSource = null;
            bs.DataSource = null;

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

            bs.DataSource = ds;
            bs.DataMember = "contacts";

            gContacts.DataSource = bs;
        }
    }